Modifying values in ConcurrentHashMap

不打扰是莪最后的温柔 提交于 2019-12-06 04:29:06

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.

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.)

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