Modifying values in ConcurrentHashMap

2019-05-23 02:33发布

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 ?

2条回答
我想做一个坏孩纸
2楼-- · 2019-05-23 03:16

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. i.e. 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.

查看更多
在下西门庆
3楼-- · 2019-05-23 03:39

CHM guarantees that those operations (e.g. 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.)

查看更多
登录 后发表回答