1. Concurrenthashmap Introduction:
Concurrenthashmap is a thread-safe Hash Table whose main function is to provide a set of methods with the same hashtable functionality but thread-safe. Concurrenthashmap can be read data without locking , and its internal structure allows it to write operations can keep the granularity of the lock as small as possible , Not to the whole concurrenthashmap locking .
2. Internal structure of the CONCURRENTHASHMAP:
Concurrenthashmap in order to improve their concurrency, in the internal use of a structure called segment, a segment is actually a class hash table structure, segment internal maintenance of a list of arrays, Let's take a look at the internal structure of Concurrenthashmap in the following picture:
From the above structure we can see that the process of locating an element requires two hash Concurrenthashmap, the first hash is positioned to segment, The second hash is positioned to the head of the linked list where the element is located , so the side effect of this structure is that the hash process is longer than the normal HashMap , but the benefit is that the write operation can Only the segment of the element is locked, it will not affect the other segment, so that, in the best case, Concurrenthashmap can support the maximum number of simultaneous write operations segment (These write operations are distributed very evenly across all segment), so the concurrency of Concurrenthashmap can be greatly improved through this structure.
(1) Segment:
Let's take a look at the data structure of segment in detail:
1 Static Final classSegment<k,v>extendsReentrantlockImplementsSerializable {2 transient volatile intcount;3 transient intModcount;4 transient intthreshold;5 transient volatileHashentry<k,v>[] table;6 Final floatLoadfactor;7}
Explain in detail the meaning of the member variables inside the segment:
- Count:number of elements in segment
- Modcount: The number of operations that affect the size of the table (such as a put or remove operation)
- Threshold: threshold , the number of elements inside the segment exceeds this value, the segment will be enlarged
- Table: An array of linked lists , each of which represents the head of a linked list
- Loadfactor: load factor , used to determine threshold
(2) Hashentry:
The elements in segment are stored as Hashentry in the list of linked lists, and look at the structure of the Hashentry:
1 static final class hashentry<k,v> 2 final K key; 3 int hash; 4 volatile V value; 5 next; 6 }
You can see a feature of Hashentry, in addition to value, a few other variables are final, this is to prevent the structure of the list is broken, there is a concurrentmodification situation.
Java Basic Knowledge Enhancement Collection Framework Note 76:concurrenthashmap's Concurrenthashmap introduction