if (!map.containsKey(key)) 
   return map.put(key, value);
else
   return map.get(key);

Thread A calls containsKey and finds out that the key is not present, but is immediately suspended.
Thread B calls containsKey and finds out that the key is not present, and has the time to insert its value v2.
Thread A resumes and inserts v1, "peacefully" overwriting (since put is threadsafe) the value inserted by thread B.

在多线程的环境中,必须使用 ConcurrentHashMap.putIfAbsent(K key, V value) 方法


方老司
2k 声望224 粉丝

教育皆祸害,[链接]