1. Dead loop problem with HashMap multithreaded insert in JDK1.7
The capacity of HashMap is limited. After multiple element inserts, HashMap will reach a certain saturation, and the probability of hash conflicts in Key mapping positions will increase. At this point, the HashMap needs to expand its length by resize.
Hashmap.size () >= Capacity * LoadFactor, where Capacity is the length of the original HashMap and LoadFactor is the LoadFactor (0.75 by default).
The resize of a HashMap creates an empty array of entries twice as long as the original one (the original capacity of the HashMap was 16). After expansion, HashMap needs to be rehash. The hash formula is index = HashCode (key)& (length-1).
HashMap before resize:
HashMap after resize:
In the multi-threaded case: Suppose a HashMap has reached the critical point of resize. At this point, two threads A and B perform A put operation on the HashMap at the same time. Since Java7 uses header interpolation to resolve hash conflicts, threads A and B may form A linked loop during the rehash process, causing an infinite loop.
2. Why is HashMap in JDK8 still thread unsafe?
In JDK8, the use of HashMap is not just for inserting data, although tail interpolation is used instead of head interpolation when using zip to resolve hash collisions. 1.8 does solve the dead-chain problem, but it is still possible to modify HashMap in multi-threaded situations. For example, if multiple threads change the value of a Key in a HashMap at the same time, the previous thread’s changes may be overwritten by subsequent threads, and the HashMap is not thread-safe. So in Java8 HashMap is only thread safe for inserting data, but not thread safe for modifying it.