简体   繁体   中英

Why does concurrentHashMap need an array of Segment? Why cant it acquire lock on node?

I was reading this article to understand how ConcurrentHashMap worked internally. https://dzone.com/articles/how-concurrenthashmap-works-internally-in-java

But I do not understand use of Segments here. It is public final Segment[] segments = new Segment[32] in this article. Before i read this article, my understanding was there would be multiple Entry tables & each segment would hold reference of one array of the multiple.But in this article there is only one

 protected transient Entry[] table; 

My question -

1) Will this above single array " table " hold entry for all the segments ? Meaning - If I put 2 entries in ConcurrentHashMap,which would return 2 different segments, would it still go under same entry table above? I am confused why aren't there multiple arrays for each segment defined above?

2) Instead of using segment and locking it, when cant a lock be acquired Entry object and perform write/update ?

Will this above single array "table" hold entries for all the segments?

Yes.

I am confused why aren't there multiple arrays for each segment defined above?

Because, the Segment objects really serve as locks for segments of the main entries array. The segments are conceptual "slices" of the main array.

Instead of using segment and locking it, when cant a lock be acquired Entry object and perform write/update ?

An operation that updates the ConcurrentHashMap will typically read and write the main entries array. Simply locking one Entry is not sufficient to perform table insertions and deletions safely.


If the descriptions in that article are confusing, you could also look at the source code directly; eg http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/concurrent/ConcurrentHashMap.java/

there are no array of segments in concurrenthashmap since java 8 onward. it directly has array of Node

Java 8 onward there is no segment array, lock is acquired on the first node of the LinkedList of a particular hashed index/bucket of the internal hash table array. ConcurrentHashMap internal

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