简体   繁体   中英

Modifying values in ConcurrentHashMap

In ConcurrentHashMap there is concept of segmentation. What it means if two threads are trying to access ConcurrentHashMap they it gets divided in two blocks and default size of blocks is 16.

Now suppose in a scenario where ConcurrentHashMap has only two elements and two different threads comes and thread1 tries to modify first value and thread2 tries to modify second value. In this case whether ConcurrentHashMap will go for segmentation?

Now in a different scenario both the threads try to modify same value how ConcurrentHashMap will handle this situation? By using locking mechanism or is there something else ?

ConcurrentHashMap has several buckets. Keys are mapped, based on their hash value, into one of the buckets. When you add or retrieve a value, the bucket associated with that key is locked.

In the case of your first question, there are two possibilities: either both keys live in the same bucket, or they live in different buckets. In the first case, only one thread can work at a time -- the first one to acquire the lock will grab it and work, the second thread will wait its turn. In the second case, where the keys are in different buckets, they'll each acquire independent locks and do their work concurrently.

For your second question, it is the bucket that gets locked, and nothing else. If two threads try to store two values for the same key, then ConcurrentHashMap promises that one of the two values will be associated with the key. ie if thread A runs map.put("Answers",2); and thread B runs map.put("Answers",10); , then ConcurrentHashMap will ensure that the map is valid and contains either 2 or 10 for "Answers" , but it won't make any promises about which of those two it is.

CHM guarantees that those operations (eg put , putIfAbsent , etc.) won't overlap, and yes, that's done with locking. Each segment of the CHM has its own lock that gets taken whenever you're modifying that segment.

(For reference, as @Affe pointed out, if you're modifying the contents of a value in the ConcurrentHashMap , CHM doesn't do -- can't do -- anything to make that thread safe.)

First of all , new implementation of CHM doesn't use Segments at all, it still uses array of nodes, if node in given index doesn't exist and two threads are trying to insert two entries with hashcode that equals to given index then CHM uses CAS , otherwise if node exists then CHM uses lock on the first element of this node to put new value. Reads in CHM are non blocking and use happen before guarantee with the help of atomic reads from Unsafe class. Check out my blog about CHM for more details https://strogiyotec.github.io/pages/posts/chm.html

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