简体   繁体   English

在多线程环境中同步 HashMap 仅用于放置和删除

[英]Synchronize HashMap in multithreaded environment only for put and remove

I have two thread that shares a common HashMap, one thread will always insert an objects to the Map and the second thread will remove objects from the HashMap.我有两个线程共享一个共同的 HashMap,一个线程将始终将对象插入 Map,第二个线程将从 HashMap 中删除对象。 my question is if this is the only logic of the two thread should I "protect" the Map with synchronize or ConcurrentHashMap, could I have a race condition?我的问题是,如果这是两个线程的唯一逻辑,我应该使用同步或 ConcurrentHashMap“保护”Map,我可以有竞争条件吗? if yes can you please explain what is the risk of not protecting the Map.如果是,请解释不保护 Map 的风险是什么。

thanks谢谢

could I have a race condition我可以有比赛条件吗

Yes, without synchronization or ConcurrentHashMap .是的,没有同步或ConcurrentHashMap

It is clearly stated in the Javadoc of HashMap :HashMap的 Javadoc 中有明确说明:

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.如果多个线程同时访问hash map,并且至少有一个线程在结构上修改了map,则必须对外同步。

You have two threads modifying the map structurally, so you need to synchronize if you use HashMap .您有两个线程在结构上修改 map ,因此如果您使用HashMap ,则需要同步。

please explain what is the risk of not protecting the Map请解释不保护 Map 的风险是什么

Undefined behavior, ranging from doing completely the wrong thing (the very best kind of undefined behavior, because you know it needs fixing), down to seeming to work, until you change your JVM version and it mysteriously stops working (the very worst kind of undefined behavior).未定义的行为,从做完全错误的事情(最好的未定义行为,因为您知道它需要修复),到看起来可以工作,直到您更改 JVM 版本并且它神秘地停止工作(最糟糕的一种未定义的行为)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM