简体   繁体   中英

ConcurrentHashMap why locking segments?

ConcurrentHashMap does optimization by locking the segments in place of locking the whole map. Wondering why can't it lock the key for better performance.

  1. You can't know synchronization policy for the key. Locking on the key can lead to unexpected behaviour and deadlocks because user code already held lock on the key.

  2. You can treat segment like inner HashMap that serves only subset of hash codes. It need for effective access to the elements. So you should block access to the whole structure not only for one key. Otherwise you risk broke internal data structers due to non-synchronized modification.

Basically, Segment = HashCode . HashCodes are not unique to each key (two different keys can have the same HashCode ), and HashMaps store based on HashCode .

Now, you shouldn't worry too much about the implementation of that, but basically, each segment is the smallest unit of isolated space , AKA, altering/removing/adding an item to a segment could affect other accesses to that segment.

So Segment is locked because that is the smallest space unit that is safe for all possible access cases.

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