Collections分析之SynchronizedList

Collections中有SynchronizedList方法

  1. @ThreadSafe  

  2. class GoodListHelper <E> {  

  3.     public List<E> list = Collections.synchronizedList(new ArrayList<E>());  

  4.   

  5.     public boolean putIfAbsent(E x) {  

  6.         synchronized (list) {  

  7.             boolean absent = !list.contains(x);  

  8.             if (absent)  

  9.                 list.add(x);  

  10.             return absent;  

  11.         }  

  12.     }  

  13. }  



上面是一個對已有的同步的list增加一個線程安全的方法。

但是爲什麼鎖要加list呢?看看源碼:

  public static <T> List<T> synchronizedList(List<T> list) {
return (list instanceof RandomAccess ?
                new SynchronizedRandomAccessList<T>(list) :
                new SynchronizedList<T>(list));
    }


由源碼可知,list是RandomAccess的子類,所以,產生SynchronizedRandomAccessList:

SynchronizedRandomAccessList繼承自SynchronizedList,SynchronizedList繼承自SynchronizedCollection,SynchronizedRandomAccessList裏方法的同步都是用的mutex,mutex是一個object,在SynchronizedCollection中定義的,在構造函數中使其爲本身。

所以上面的代碼需要使用list作爲同步鎖了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章