多线程环境同步HashMap只做put和remove
Synchronize HashMap in multithreaded environment only for put and remove
我有两个共享一个公共 HashMap 的线程,一个线程总是将一个对象插入到 Map 中,第二个线程将从 HashMap 中删除对象。
我的问题是,如果这是两个线程的唯一逻辑,我应该用同步或 ConcurrentHashMap 来“保护”Map,我可以有竞争条件吗?
如果是,请您解释一下不保护地图的风险是什么。
谢谢
could I have a race condition
是,没有同步或 ConcurrentHashMap
。
在Javadoc of HashMap
中明确说明:
Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.
你有两个线程在结构上修改地图,所以如果你使用HashMap
,你需要同步。
please explain what is the risk of not protecting the Map
未定义的行为,从完全错误的事情(最好的未定义行为,因为你知道它需要修复),到似乎有效,直到你更改您的 JVM 版本,它会神秘地停止工作(最糟糕的一种未定义行为)。
我有两个共享一个公共 HashMap 的线程,一个线程总是将一个对象插入到 Map 中,第二个线程将从 HashMap 中删除对象。 我的问题是,如果这是两个线程的唯一逻辑,我应该用同步或 ConcurrentHashMap 来“保护”Map,我可以有竞争条件吗? 如果是,请您解释一下不保护地图的风险是什么。
谢谢
could I have a race condition
是,没有同步或 ConcurrentHashMap
。
在Javadoc of HashMap
中明确说明:
Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.
你有两个线程在结构上修改地图,所以如果你使用HashMap
,你需要同步。
please explain what is the risk of not protecting the Map
未定义的行为,从完全错误的事情(最好的未定义行为,因为你知道它需要修复),到似乎有效,直到你更改您的 JVM 版本,它会神秘地停止工作(最糟糕的一种未定义行为)。