Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What is the principle of JDK7 HashMap ring generation?

Shulou Source: shulou.com Published: 2022-06-01 18:28:38 11月13日 Update

What is the principle of JDK7 HashMap ring generation? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

In JDK7, when we use head insertion to relocate the old table data to the new table, we know that it will travel the loop. The core function transfer generated by the ring is as follows, in which the key part is marked.

Under normal circumstances:

In the case of concurrency, for example, if I have two threads performing put data and capacity expansion operations at the same time, thread 1 only executes Entry next = e.next and is suspended, while thread 2 finishes normal execution. The result is as follows:

After thread 2 finishes execution, thread 1 then executes the following statement from the original pause:

Through step-by-step analysis and drawing, we can know that there will be rings in the red part. HashMap is not safe in JDK, and ConcurrentHashMap should be used in multithreaded cases.

7vs8

I used Hash for 4 times in 7 and only once in 8.

7 = array + linked list, 8 = array + linked list + red-black tree

7 is the head insertion method, multi-thread is easy to cause the ring, 8 is the tail insertion method.

The expansion of 7 is to relocate all the data, while in 8, the location is unchanged and the old size size is moved to achieve better.

7 is to determine whether to expand capacity and then insert, and 8 is to insert first and then to see whether to expand capacity.

HashMap is not safe on site regardless of 78. Remember to use ConcurrentHashmap in the case of multithreading. ConcurrentHashmap's next article says.

common problem

Random search for some common HashMap problems, if you understand the above code to deal with these should be no problem.

HashMap principle, internal data structure.

The general process of put,get,remove in HashMap.

The implementation of hash function in HashMap.

How to expand HashMap.

Why several important parameters of HashMap are set in this way.

Why HashMap is not thread-safe and how to replace it.

The difference between HashMap in JDK7 and JDK8.

Switch between linked list and red-black tree in HashMap.

The answer to the question about the generation principle of the JDK7 HashMap ring is shared here. I hope the above content can be of some help to everyone. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Tags: Threads problems situations data principles security functions common arrays more parts analysis positioning help solutions easy important simple two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple macOS Redmi OPPO Reno MariaDB