在早期的JDK中,有兩種現成的實現,Vector和Hashtable,可以直接new對象獲取;
在JDK1.2中,引入了同步封裝類,可以由Collections.synchronizedXxxx等方法創建;
同步容器類雖然都是線程安全的,但是在某些情況下(復合操作),仍然需要加鎖來保護;
常見復合操作如下:
舉個條件運算的例子,代碼如下:
package concurrency.old;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//線程任務類,獲取集合中的最後一個元素
class GetLast implements Runnable{
private Vector<Integer> list;
public GetLast(Vector<Integer> list) {
this.list = list;
}
@Override
public void run() {
while(true){
try{
Test.getLast(list);
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage() + " --- in class GetLast");
break;
}
}
}
}
//線程任務類,刪除&添加元素
class DeleteAndAdd implements Runnable{
private Vector<Integer> list;
public DeleteAndAdd(Vector<Integer> list) {
this.list = list;
}
@Override
public void run() {
while(true){
try{
Test.deleteAndAdd(list);
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage() + " --- in class DeleteAndAdd");
break;
}
}
}
}
public class Test {
//獲取最後一個元素
public static Integer getLast(Vector<Integer> list){
//這裡根據list.size()得到最後一個元素的索引
//換句話說,這條語句已經檢查認為在集合list中存在索引為list.size() - 1的元素
int lastIndex = list.size() - 1;
if(lastIndex < 0) return null;
//返回指定索引處的元素
return list.get(lastIndex);
}
//刪除元素,添加元素
public static void deleteAndAdd(Vector<Integer> list){
int lastIndex = list.size() - 1;
if(lastIndex < 0) return;
list.remove(lastIndex);
list.add(3);
}
public static void main(String[] args) {
Vector<Integer> vector = new Vector<Integer>();
vector.add(1);
vector.add(2);
ExecutorService exec = Executors.newCachedThreadPool();
GetLast gl = new GetLast(vector);
DeleteAndAdd daa = new DeleteAndAdd(vector);
exec.execute(gl);
exec.execute(daa);
}
}
運行以上程序,很快發現在getLast中拋出了java.lang.ArrayIndexOutOfBoundsException異常,原因在於getLast方法不是原子操作,調用size方法和get方法之間,其它線程執行了remove操作,導致容器大小變小,索引訪問越界,拋出異常。
若想得到正確結果,可修改代碼,對getLast和deleteAndAdd方法裡的操作加鎖(因為Vector內部是通過自身對象作為鎖的,所以這裡同樣以Vector對象作為鎖),使之成為原子操作,如下代碼:
//獲取最後一個元素
public static Integer getLast(Vector<Integer> list){
synchronized(list){
//這裡根據list.size()得到最後一個元素的索引
//換句話說,這條語句已經檢查認為在容器list中存在索引為list.size() - 1的元素
int lastIndex = list.size() - 1;
if(lastIndex < 0) return null;
//返回指定索引處的元素
return list.get(lastIndex);
}
}
//刪除元素,添加元素
public static void deleteAndAdd(Vector<Integer> list){
synchronized(list){
int lastIndex = list.size() - 1;
if(lastIndex < 0) return;
list.remove(lastIndex);
list.add(3);
}
}
另外,在對vector的元素遍歷時(for循環方式),其它線程刪除了容器中的一個元素,也會拋出異常java.lang.ArrayIndexOutOfBoundsException異常,原因與上面提到的getLast方法一樣,在訪問最後一個元素的時候越界了;
for(int i = 0; i < vector.size(); i++){
System.out.println(vector.get(i));
}
一個可行的修改方式同樣是對容器加鎖,但代價較大,導致其它線程在迭代期間不能訪問容器,降低了並發性;
synchronized(vector){
for(int i = 0; i < vector.size(); i++){
System.out.println(vector.get(i));
}
}
同步容器與非同步容器一樣,在迭代期間,若其它線程並發修改該容器,會拋出ConcurrentModificationException異常,即快速失敗機制,之前有寫過相關內容,詳見下面鏈接:
http://www.cnblogs.com/chenpi/p/5270990.html
通過在容器迭代期間對容器加鎖來解決該問題是一種方式,但並發性差,當容器規模大時,更加嚴重,而且還可能產生死鎖問題;一種更優的解決方式,如上面鏈接裡提到的,采用克隆容器(CopyOnWriteArrayList等),在副本上進行操作,但存在顯著的性能開銷,需要拷貝數組等操作,這種方式的好壞要看具體需求,如容器大小,執行的具體操作,調用頻率等,一般當迭代操作遠多於修改操作時,比較適用克隆容器;
另外,在集合中,有一些隱藏的迭代操作,如toString,equals,hashCode等方法,使用時需注意,也可能會拋出ConcurrentModificationException異常;
同步容器對所有容器狀態的訪問都串行化,嚴重降低了並發性;當多個線程競爭鎖時,吞吐量嚴重下降;
java5.0之後提供了多種並發容器來改善同步容器的性能,如ConcurrentHashMap、CopyOnWriteArrayList、CopyOnWriteArraySet、ConcurrentSkipListMap等;
這裡主要看下ConcurrentHashMap;
采用分離鎖技術,同步容器中,是一個容器一個鎖,但在ConcurrentHashMap中,會將hash表的數組部分分成若干段,每段維護一個鎖,以達到高效的並發訪問;
迭代器弱一致性,迭代期間不會拋出ConcurrentModificationException異常;
size()、isEmpty()等方法返回的是一個近似值;
增加了若干原子操作方法,如putIfAbsent(沒有改key,則添加);