简体   繁体   中英

Using ConcurrentHashMap

I'm new to threading in Java and I need to access data structure from few active threads. I've heard that java.util.concurrent.ConcurrentHashMap is threading-friendly. Do I need to use synchronized(map){} while accessing ConcurrentHashMap or it will handle locks itself?

It handles the locks itself, and in fact you have no access to them (there is no other option)

You can use synchronized in special cases for writes, but it is very rare that you should need to do this. eg if you need to implement your own putIfAbsent because the cost of creating an object is high.

Using syncrhonized for reads would defeat the purpose of using the concurrent collection.

ConcurrentHashMap is suited only to the cases where you don't need any more atomicity than provided out-of-the-box. If for example you need to get a value, do something with it, and then set a new value, all in an atomic operation, this cannot be achieved without external locking.

In all such cases nothing can replace explicit locks in your code and it is nothing but waste to use this implementation instead of the basic HashMap .

Short answer: no you don't need to use synchronized(map) .
Long answer:

  • all the operations provided by ConcurrentHashMap are thread safe and you can call them without worrying about locking
  • however, if you need some operations to be atomic in your code, you will still need some sort of locking at the client side

No, you don't need, but if you need to depend on internal synchronization, you should use Collections.synchronizedMap instead. From the javadoc of ConcurrentHashMap :

This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

Actually it won't synchronize on the whole data structure but on subparts (some buckets) of it. This implies that ConcurrentHashMap 's iterators are weakly consistent and the size of the map can be inaccurate. (But on the other hand it's put and get operations are still consistent and the throughput is higher)

There is to note for concurrenthmp feature it provides, which is fail safe iterator. 功能还有值得注意的 ,即故障安全迭代器。 Use CHMP just because they want to edit the entryset for put/remove while iteration. Collections.synchronizedMap(Map) is other one. But ConcurrentModificationException may come in the above case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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