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) 方法
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论