java - 多線程并發(fā)情況下Map.containsKey() 判斷有問題
問題描述
有下面一段代碼:
package test;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap;public class TestContain extends Thread{ private final String key = 'key'; private final static ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();private static Object getLock(String lockName) { if (!locks.containsKey(lockName)) {//這一句會存在并發(fā)問題locks.put(lockName, new String('我是值'));System.out.println('加了一次'); } return locks.get(lockName);}@Overridepublic void run() { getLock(this.key);};public static void main(String[] args) { for (int i = 0; i < 20; i++) {new TestContain().start();; }}}
輸出結果:
加了一次加了一次加了一次
表明了Map.containsKey() 在多線程的情況下會判斷不準確。
這是為什么呢? 有什么方法改進呢?
問題解答
回答1:ConcurrentHashMap的doc上有一段
Retrieval operations (including <tt>get</tt>) generally do not block, so may overlap with update operations (including
<tt>put</tt> and <tt>remove</tt>). Retrievals reflect the results of the most recently completed update operations holding upon their onset.
里面的get方法并不加鎖,get方法只是拿到最新完成update的值。
所以題主方法中的locks.containsKey(lockName)沒有鎖來保證線程安全的。而且感覺ConcurrentHashMap的使用場景并不是用containsKey來保證更新操作只進行一次,而是用putIfAbsent來保證。
回答2:ConcurrentMap保證的是單次操作的原子性,而不是多次操作。
你的getLock函數(shù)中包含了多次操作,ConcurrentMap沒法擴大它的同步范圍,你需要自己實現(xiàn)getLock的鎖。
回答3:使用putIfAbsent方法。
相關文章:
1. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語法實現(xiàn)存在即更新應該使用哪個標簽?2. mysql - 數(shù)據(jù)庫建字段,默認值空和empty string有什么區(qū)別 1103. mysql - 這種分級一對多,且分級不平衡的模型該怎么設計表?4. Navicat for mysql 中以json格式儲存的數(shù)據(jù)存在大量反斜杠,如何去除?5. mac OSX10.12.4 (16E195)下Mysql 5.7.18找不到配置文件my.cnf6. mysql mysql_real_escape_string() 轉義問題7. 新人求教MySQL關于判斷后拼接條件進行查詢的sql語句8. mysql - 千萬數(shù)據(jù) 分頁,當偏移量 原來越大時,怎么優(yōu)化速度9. MySQL FOREIGN KEY 約束報錯10. mysql - 數(shù)據(jù)庫表中,兩個表互為外鍵參考如何解決
