One: HashMap
---> The underlying storage is entry<k,v>[] Array
The structure of the--->Entry<K,V> is a one-way linked list
Static Class Entry<k,v> implements Map.entry<k,v> {
Final K Key;
V value;
Entry<k,v> Next;
int hash;
/**
* Creates new entry.
*/
Entry (int h, K K, v V, entry<k,v> N) {
Value = V;
Next = n;
key = k;
hash = h;
}
}
---> Save or remove the location.
(1) When the key is stored, take the key Hascode, then hascode a series of bitwise AND, bitwise XOR and finally get a number, and then take this number and entry[] array length minus one to bitwise AND operation, to find out the array subscript to store.
(2) Get the entry object on the array, and then iterate over the hashcode comparison of the key. If the hashcode is the same, then the equals comparison content. If all are the same, then the same key is substituted. If there is no equality, then a new entry object is added to the end of the linked list.
(3) If you take the object as key. Be sure to override this object's Hashcode method and the Equals method. Make sure that storage and lookup are normal.
(4) Different object Hascode may be the same, so be sure to override the Equals method.
Two: Concurrenthashmap
---> Bottom is a segment<k,v>[] array. Hash the key first, get the subscript of the segment array, and then store the data in the Hashentry array inside the segment object. This storage and Hasmap is the same.
--->Segment<K,V> objects are reentrantlock objects that inherit the re-entry lock.
---> A hashentry<k,v>[] array is stored inside each segment element
---> In the future each Key-value pair is converted into Hashentry object.
The structure of--->hashentry is also a unidirectional linked list structure
---> This class takes advantage of the CAS operation and the lock method provided by the unsafe class. Achieve thread safety and efficiency. The so-called segmented lock technique is to store elements in multiple containers, each with its own lock. Distribute the pressure of a single lock to multiple locks. Greatly reduces the occurrence of mutexes. Also because there is no use of the synchronized of the heavy-lock. The locking mechanism for concurrent packages is used. And the locking mechanism of the contract, relies on the JDK's unsafe class to provide atomic operations, and thread blocking technology to achieve synchronization.
Locks are used when---> storage.
---> Read the method of using the voliate semantics provided by the unsafe to read the memory directly.
Static Final class Hashentry<k,v> {
final int hash;
Final K Key;
volatile V value;
Volatile hashentry<k,v> next;
Hashentry (int hash, K key, V value, hashentry<k,v> next) {
This.hash = hash;
This.key = key;
This.value = value;
This.next = Next;
}
}
Java Multithreading: Comparison of Concurrenthashmap and JDK HashMap in the contract