JDK1.7 ConcurrentHashMap source code analysis, concurrenthashmap
Overview
ConcurrentHashMap is a thread-safe version of HashMap. It uses the multipart Lock solution to achieve better performance in high concurrency.
AnalysisJDK1.7ConcurrentHashMap implementation in.
ConcurrentHashMap Overview
HashMap is NOT thread-safe. To ensure thread security, unless it is locked, the performance is very low. ConcurrentHashMap divides the entire HashMap array into several segments, each of which has an array. When adding a Key, you need to calculate its Segment Based on the hash value, and then calculate the position in the Segment based on the hash value. Segment inherits from ReentrantLock, and each Segment is a lock. In the case of multiple threads, the lock competition is reduced and the performance is improved.
Shows the ConcurrentHashMap storage structure:
Public ConcurrentHashMap (int initialCapacity, float loadFactor, int concurrencyLevel) {if (! (LoadFactor> 0) | initialCapacity <0 | concurrencyLevel <= 0) throw new IllegalArgumentException (); if (concurrencyLevel> MAX_SEGMENTS) concurrencyLevel = MAX_SEGMENTS; // Find power-of-two sizes best matching arguments int sshift = 0; int ssize = 1; // concurrencyLevel is the concurrency level, this step is to calculate the nth power of 2, which is greater than the concurrencyLevel. // Why not use the Integer in HashMap. highestOneBit (number-1) <1) to calculate this value // in my understanding, concurrencyLeve L generally, it is relatively small (the default value is 16). Using this calculation method is more efficient. While (ssize <concurrencyLevel) {++ sshift; ssize <= 1 ;}// this is required for calculating the segment position based on hash. segmentShift = 32-sshift; this. segmentMask = ssize-1; if (initialCapacity> MAXIMUM_CAPACITY) initialCapacity = capacity; // calculate the table length int c = initialCapacity/ssize in each segment; if (c * ssize <initialCapacity) ++ c; int cap = MIN_SEGMENT_TABLE_CAPACITY; while (cap <c) cap <= 1; // create segments and segments [0] Segment <K, v> s0 = new Segment <K, V> (loadFactor, (int) (cap * loadFactor), (HashEntry <K, V> []) new HashEntry [cap]); segment <K, V> [] ss = (Segment <K, V> []) new Segment [ssize]; UNSAFE. putOrderedObject (ss, SBASE, s0); // ordered write of segments [0] this. segments = ss ;}
The biggest difference from HashMap is that it has more Segment initialization.
The Size of the Segment is also initialized to the Npower of 2, which provides a simple method for the overall Map resize and determining the Segment where a hash value is located.
The table in each Segment is the same as the table in HashMap. Next, let's see how to calculate the position of the Segment in PUT.
PUT
Public V put (K key, V value) {Segment <K, V> s; if (value = null) throw new NullPointerException (); int hash = hash (key ); // get the Key's Segment position int j = (hash >>> segmentShift) & segmentMask; if (s = (Segment <K, V>) UNSAFE. getObject // nonvolatile; recheck (segments, (j <SSHIFT) + SBASE) = null) // in ensureSegment s = ensureSegment (j); return s. put (key, hash, value, false );}
SegmentShift: calculated in the constructor. Assume that concurrencyLevel is 16, segmentShift = 28 (32-4)
SegmentMask: 15 (16-1)
It can be seen that the algorithm used to find the Segment where the Key is located is the same as that in the table where the Key is located in HashMap. The algorithm is hash & (length-1 ).
Therefore, the length of the Segment must also be the N power of 2.
Hash >>> segmentShift is to use the hash high level for calculation.
The s. put method puts the Key in the response position of the table in the Segment. Its algorithm is similar to that in HashMap, but the lock is added.
Thread Security HashMap-non-thread security
The following code is used to Put a Key:
Void createEntry (int hash, K key, V value, int bucketIndex) {// 1. obtain the Linked List Entry <K, V> e = table [bucketIndex]; // 2. set the new Key to the first table [bucketIndex] = new Entry <> (hash, key, value, e); size ++;} of the linked list ;}
Assume that there are two threads A and B, and perform Step 2 at the same time. The obtained e is the same, for example, x, y, and z.
Then thread A runs to step 2, adds a new element a to e, and assigns A value to table [bucketIndex]. In this case, table [bucketIndex] is a, x, y, z
Then thread B runs to step 2, adds a new element B to e, and assigns a value to table [bucketIndex]. In this case, table [bucketIndex] is B, x, y, z.
In this case, there will be problems. This is just an example, so HashMap is non-thread-safe.
ConcurrentHashMap-thread security
Use the following code to Put a Key to a Table:
final V put(K key, int hash, V value, boolean onlyIfAbsent) { HashEntry<K,V> node = tryLock() ? null : scanAndLockForPut(key, hash, value); V oldValue; try { ...... } finally { unlock(); } return oldValue;}
We can see that the Lock is added to put, which ensures the thread security.
Check the source code of ConcurrentHashMap. We can find that the remove and replace of ConcurrentHashMap may cause thread security problems.
The Get method of ConcurrentHashMap is not completely thread-safe, because there is no lock in Get, but JDK uses many volatile type variables to ensure thread security in most cases.
For details about thread insecurity, refer to: in-depth analysis of ConcurrentHashMap
Summary:
ConcurrentHashMap is thread-safe in most cases. Use ConcurrentHashMap in multiple threads.
Refer:
1. Recognition of HashMap http://tech.meituan.com/java-hashmap.html in Java 8 series
2. In-depth analysis of ConcurrentHashMap http://ifeve.com/java-concurrent-hashmap-2
3. jdk8 ConcurrentHashMap source code parsing http://jahu.iteye.com/blog/2331191