Java ConcurrentHashMap not thread safe.. wth?

泪湿孤枕 提交于 2019-12-05 03:16:44

You need to read the javadocs for the ConcurrentHashMap.values() method, paying special attention to this description of how the iterator for the values() collection works:

"The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction."

The iterator does not give you a consistent snapshot of the state of the values collection, but it is thread-safe, and the expected range of behaviours is clearly specified.

If you want a Map implementation that gives you a consistent snapshot of the values (or keys, or entries) in the map AND allows you to iterate concurrently with modifications, you will probably need to create a custom Map wrapper class (that copies the collections atomically) ... or a full-blown custom Map implementation. Both are likely to be a lot slower than a ConcurrentHashMap for your use-case.

java.util.concurrent.ConcurrentHashMap does not allow null value. So, null check(person != null) in your code is unnecessary.

If you want to deny modification of Map while iteration, you must use synchronization block in above code and all modification operation codes.

I don't see anything wrong with your code. Because it's unlikely that the crash actually occurs at the else, it's likely that the getGender() method is returning null.

You may find that you can't have the map get modified while you are iterating through it. If that is the case you may want to get the values and keys in a separate collection and iterate through that, as it will be immutable.

It won't be perfect, but the other option is to extend ConcurrentHashMap and when something is added or removed you update these four variables, so you don't have to iterate through the entire list each time, as that seems to be a waste of cpu cycles.

Here are a couple of links that may be useful:

This one talks a bit about the fact that the improved concurrency is because of relaxing of some promises. http://www.ibm.com/developerworks/java/library/j-jtp07233.html

memory consistency properties explained: http://download-llnw.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html#MemoryVisibility

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