HashMap multi-threaded operating results in infinite loop problem

In multi-threaded, be put HashMap operation will cause an infinite loop, because HashMap expansion resize () method. Since the expansion is to create a new array, copy the data to the original array. Since the array indexes hanging chain, it is necessary to copy the list, but may cause multithreading circular linked list. Copying the list as follows:

The following two analog threads expansion. Suppose, for the current space HashMap 2 (threshold value 1), 0 and 1 respectively, hashCode, elements A and B have the hash address 0, this time to the additive element C, C through the hash function, the hash address obtained 1, this time due to exceeding the threshold, the space is not enough, you need to call resize method for expansion, so in multithreaded conditions, competitive conditions will be simulated as follows:


Thread one: read HashMap to the current situation, in preparation for the expansion, thread two intervention

Thread II: read HashMap, for expansion

Thread one: Continue

This process is copied to the new A first hash table, and then subsequently copied to the head of the chain B (the front A: B.next = A), originally B.next = null, this is over (with thread two of the same process), however, due to the expansion of two threads, the B.next = a, therefore, here to continue copy a, let A.next = B, thus, circular linked list appears: B.next = a; A.next = B

 

Note: jdk1.8 have solved the problem of infinite loop.

Guess you like

Origin www.cnblogs.com/zhangyaotong/p/11246020.html