1. HashMap
Entry, a pair of KV is a Entry, and some next pointers are used to resolve hash conflicts.
Table, which is used internally to store entry arrays, resize when the table is multiplied.
Capacity, the length of the table array.
Loading factor, when the number of key is greater than table.length* filling factor will be expanded, default 75%.
Resize operation, synchronous recalculation of the new slot corresponding to the hash value
Put operation
Like all HashMap, hash values are calculated, the capacity is checked, and mapped to the slot. When a conflict occurs, it is inserted at the back of the entry list.
However, Java has also made an optimization, the list length when more than 8 will optimize him to an orderly tree.
Get operation
Find the slot according to the hash value, then compare the first entry to find the KV, not the words, follow the next pointer to the entry down.
If, found to be a tree not a linked list, do an orderly search directly
2. Concurrenthashmap
The following is not the same place as HashMap.
Problem, concurrenthashmap How to initialize table in multi-threaded case, and table in multithreaded case resize
Solve
There is a Sizectl attribute, this property can only be 0 or-1, through CAs, only one thread set him to-1.
Other threads that did not set a successful call Thread.yield, the exact words are "lost initialization race; Just spin "
Problem, put when the slot has no value before, how to prevent multiple threads to set the new value at the same time
Solve
Try to update this empty location with CAs, when the update fails, the first node on the slot is locked, inserted into the linked list or TreeNode
Problem, put to size++ later
Solve
Instead of using Atomicinteger, each slot corresponds to a countercell that represents the number of entry in this slot, and there is no reason to read why Countercell is used.
Problems, resize related strategies
Solve
Before using the filling factor and quantity to determine whether the need for RESIZE,JAVA8 is to expand by whether there is a hash conflict.
Like the Redis strategy, JAVA8 also uses a progressive hash.
HashMap and concurrenthashmap,java1.8 versions