concurrentmap并非线程安全

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) 方法

你可能感兴趣的:(java)