About HashMap is the reason why the thread-safe

We know hashmap expansion factor is 0.75, if the array length hashmap have used 75% will lead to expansion, a new application will twice the original length of the bucket array,

Then remap the original elements of the array to the new array, one by one the original reference data is set to null. That is, resize () when the expansion will cause the thread-safe.

In addition, when you want to insert a new node of the list hashmap, before jdk1.8 version is inserted in the head, after 1.8 is inserted in the tail.

So when hashmap for expansion of it? When the number of elements exceeds hashmap * loadFactor array size, the array will be the expansion, loadFactor default value is 0.75, that is, by default, the size of the array 16,

When the number of elements in then hashmap than 16 * 0.75 = 12 when the size of the extended array is put 2 * 16 = 32, i.e., doubled, and then re-calculates the position of each element in the array, which is a consuming operation performance,

So the number of elements in hashmap If we had to predict, then the default size of the array can effectively improve the performance of hashmap.

For example, we have 1000 elements new HashMap (1000), but in theory new HashMap (1024) is more appropriate, but above annegu have said, even 1000, hashmap automatically sets it to 1024.

But new HashMap (1024) is not more appropriate, since 0.75 * 1024 <1000, that is to say in order to allow 0.75 * size> 1000, so we need new HashMap (2048) was the most appropriate to avoid resize issues.

Unsafe reasons:

(1) put in the time, because this method is not synchronized, if there are two threads A, B hash key to put a value thereof is the same, whether it is inserted into the head or the tail is inserted, the insertion position acquired if A is x ,

    However it has not been inserted, then B can also be calculated as the insertion position x, regardless of the sequence of AB inserted certainly a lost;

(2) at the time of expansion, before using the first interpolation method is jdk1.8, when two threads simultaneously detected hashmap capacity is needed, while performing time expansion may cause circular list,

     The main reason is that the first order interpolation using the new and the old list is the list opposite, after the end of 1.8 using interpolation such a problem does not occur, while if it exceeds 1.8, the length of the list will be transformed into red-black trees 8 .



Guess you like

Origin www.cnblogs.com/ZJOE80/p/12563552.html