问题
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 ?
回答1:
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.
回答2:
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.)
来源:https://stackoverflow.com/questions/15909425/modifying-values-in-concurrenthashmap