Extending HashMap<K,V> and synchronizing only puts

坚强是说给别人听的谎言 提交于 2019-12-05 13:26:47

since get() can be reading a changing data structure, everything bad can happen.

I've seen get() trapped in dead loop, so it's not just a theoretical possibility, bad things do happen.

I hope you are also synchronizing on putAll and remove. putAll especially since multiple threads can try and resize your HashMap. Those methods too will be updating size and modCount which if done outside of synchronization can result in lost updates.

As I mentioned in the comments, another problem that can arise is that the putAll(Map) method does not appear to be synchronized. Since putAll can also modify the structure of the Map, it is unsafe to call it unsynchronized from one thread while another thread is using the same Map.

At a higher-level though, it'd be interesting to understand more of the why around why put(key, value) was synchronized. Even if you've now guarded against unsynchronized modifications to the map's structure, it still does not seem like a good idea for multiple threads to be accessing the map without synchronization. In fact, if thread A is attempting to iterate over the HashMap's contents, and thread B calls synchronized put(key, value), the iterator in Thread A will still fail fast and throw a ConcurrentModificationException rather than do something non-deterministic.

Even if you were to synchronize the putAll(Map) call, other threads iterating over the map's contents will still see exceptions. If the Map needs to be used in multiple threads and at least one of those threads needs to modify the Map, all of the calls need to be synchronized, period.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!