標籤:避免 wap 發布 寫入 概念 problem 讀書 自己 class
這一小節給了一段代碼,
1 public class TestClass { 2 private HashMap<String, Integer> map = new HashMap<String, Integer>(); 3 public synchronized void add(String key){ 4 Integer value = map.get(key); 5 if(value == null){ 6 map.put(key,1); 7 }else{ 8 map.put(key, value + 1); 9 }10 } 11 }
可以看出,這是對一個不保證安全執行緒的容器做寫入同步。書中該代碼前的語境是這樣:
。。。不過,需要在這裡提一點的是,有時通過加鎖把使用線程不安全容器的代碼改為使用安全執行緒容器的代碼時,會遇到筆者之前遇到過的一個陷阱,即在一個使用 map 儲存資訊後統計總數的例子中,map 中的 value 整型使用線程不安全的 HashMap 代碼是這樣寫的。。。
由此可見,一開始貼的代碼是正確也推薦使用的。但之後作者在這貼了一段代碼並敘述
。。。如果我們使用 ConcurrentHashMap 來替換 HashMap,並且僅僅是去掉 synchronized 關鍵字,那麼就出問題了。問題不複雜,大家可以自己來思考答案。
代碼如下
1 public class TestClass { 2 private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); 3 public void add(String key){ 4 Integer value = map.get(key); 5 if(value == null){ 6 map.put(key,1); 7 }else{ 8 map.put(key, value + 1); 9 }10 } 11 }
這裡的 ConcurrentHashMap 是 Java 1.5 版本出的安全執行緒容器,採用分段鎖(lock striking)做細粒度的同步,針對對並發的訪問,動作的輸送量也不至於大打折扣。
乍一看好像沒有什麼不對勁的,既然選擇一個安全執行緒容器,那麼監視器可以移除也不會有什麼問題吧?
也不會有什麼問題吧?(確認+1)
也不會有什麼問題吧?(確認 again)
如果不是作者提到這是個陷阱,筆者作為個小菜鳥將來有120%的可能會掉這個坑裡。。。那就來分析下這段代碼究竟是有什麼問題吧!
可以看出的是,這個 add 方法是個 check then act 的動作,而這就會造成常見的 race condition 。來看一段 stackoverflow 上的解釋:
A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don‘t know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.
Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g:
接下來也給出簡潔的代碼闡述這一現象:
if (x == 5) // The "Check"{ y = x * 2; // The "Act" // If another thread changed x in between "if (x == 5)" and "y = x * 2" above, // y will not be equal to 10.}
上面說,並發的訪問或者更新操作,如果不加鎖控制同步,那 if 內的代碼的先決條件並不一定就是顯式 check 的,也許其他線程已經對那個資料動了手腳。到這就很明顯了,有點並發意識的朋友大概都能理解了吧。嘻嘻。
由這個代碼陷阱讓筆者想起了一些概念,一方面是本文所說的訪問操作的同步,另一方面呢,就是這個 map 的發布,也就是常說的暴露引用什麼的,要留心即使這裡鎖了這個方法,當別處的代碼也可以訪問更新這個 map 時,依舊會導致同樣的陷阱。當然,最好是直接
synchronized(map){...},直接對 map 加鎖,避免使用代碼的內建鎖。
【讀書筆記】《大型網站系統與Java中介軟體實踐》第一章1.2.2.3 同步陷阱