JDK version 1.8
The implementation of CONCURRENTHASHMAP in 1.8, almost all of the 1.7 version has been changed. First, the data structure of the segment segment lock is canceled, and the structure of the array + linked list (red-black tree) is replaced. For the granularity of the lock, adjust the locking (Node) to each array element.
The steps for put are as follows:
- Parameter Validation.
- If table[] is not created, it is initialized. Table initialization and expansion using CAS lock-free design, through the state Sizectl to control the concurrent operation of the thread: U.compareandswapint (this, Sizectl, SC,-1)
- When there is no node behind table[i], create node directly (no lock operation). Also implemented by CAS: Return U.compareandswapobject (tab, ((Long) I << Ashift) + abase, C, v);
- If you are currently expanding, help expand and return to the latest table[].
- Then append nodes to the linked list or red-black tree. This process uses synchronized (f) to lock the current node for thread safety
- If it is a linked list, traverse the linked list, find the same key replace the old value, do not find the same key is added to the end of the list
- If it's a red and black tree,
- Finally go back to determine whether to reach the threshold, such as arrival into the red and black tree structure. Method of Use: Treeifybin (tab, i);
The Get () method does not have a lock operation, the steps are as follows:
- First, locate the I in table[].
- If Table[i] exists, continue to find.
- First, the linked list header is compared, and if yes it is returned.
- Then, if it is a red-black tree, look for the tree.
- If it is not a red-black tree, loop-linked list lookup.
The detailed information on the reference network is as follows:
JDK1.8 realization of Concurrenthashmap
Java concurrency Programming 23, Concurrenthashmap Principle Analysis (version 1.7 and 1.8 contrast)