Java Fundamentals: Test, Analysis and summary of HASHMAP suspended animation lock problem

Source: Internet
Author: User
Tags rehash

Objective

Two days ago in the company's internal blog to see a colleague to share the online services hanging off cpu100% article, let me think of hashmap in the improper use of the death cycle problem, here do a collation and summary, also by the way review under HashMap.

Directly on the test code

  Depending on the machine configuration and performance, the number of threads and put quantities of the test results varies

public class Hashmapinfinitelooptest {/** * based on JDK1.7 test HashMap The situation of suspended animation in multi-threaded environment * JDK1.8 HASHMAP Implementation with 1.7 of the comparison has a great change, has not saved        In this question * (this is not a problem with the JDK, HashMap is not thread-safe, shared in a multithreaded environment must be a thread-safe map Container) */public static void main (string[] args) { String jdkver = System.getproperty ("java.version"); JDK version String Jdkmod = System.getproperty ("Sun.arch.data.model");        32-bit or 64-bit System.out.println (Jdkver + "#" + jdkmod); Final map<string, string> map = new hashmap<> ();//Final map<string, string> Map = new Concurrent        Hashmap<> (); for (int i=0, i<30; i++) {new Thread (new Runnable () {@Override public void Ru                    N () {System.out.println (Thread.CurrentThread (). GetName ()); for (int j=0; j<1000; J + +) {map.put ("" +j+ "_" +system.currenttimemillis (), "" +j+ "_" +system.current                    Timemillis ()); }}}, "MYthread_ "+i". Start (); }    }}

View the Java process by Jconsole:

Finally, you can only force the end process

Analysis

HashMap uses the hash table as its underlying storage data structure (through the array subscript to achieve fast indexing, linked list to implement element collision processing), and support dynamic expansion, mainly through the resize method, but also from this method began to problem. (Here are two interviewers like to ask: 1.table default length and size before and after expansion?) 2. Why does it require that the length of the table be 2 n times? )

Because the whole hashmap is not thread-safe, so resize also did not synchronize, if the wrong in the multi-threaded environment to share the HASHMAP is likely to cause my previous mention of the suspended animation lock problem. Dynamic expansion of the need to move the old linked list to the new hash table, if it is in a multi-threaded environment, may form a circular link list, but this time seems to be all right, only in the again put and traverse each linked list check whether there is the same key, the dead loop appears (if it is get the same situation).

Here are some of the things I have collated from https://coolshell.cn/articles/9606.html (well written):

123456789101112 void resize(int newCapacity){    Entry[] oldTable = table;    int oldCapacity = oldTable.length;    ......    //创建一个新的Hash Table    Entry[] newTable = new Entry[newCapacity];    //将Old Hash Table上的数据迁移到New Hash Table上    transfer(newTable);    table = newTable;    threshold = (int)(newCapacity * loadFactor);}

Source code of the migration, note the highlight:

1234567891011121314151617181920 void transfer(Entry[] newTable){    Entry[] src = table;    int newCapacity = newTable.length;    //下面这段代码的意思是:    //  从OldTable里摘一个元素出来,然后放到NewTable中    for (int j = 0; j < src.length; j++) {        Entry<K,V> e = src[j];        if (e != null) {            src[j] = null;            do {                Entry<K,V> next = e.next;                int i = indexFor(e.hash, newCapacity);                e.next = newTable[i];                newTable[i] = e;                e = next;            } while (e != null);        }    }}
    • Suppose our hash algorithm is simply a key mod of the size of the table (that is, the length of the array).
    • The top is the old hash table, where the hash table is size=2, so key = 3, 7, 5, after mod 2 all conflict in table[1] here.
    • The next three steps are the hash table resize into 4, and then all <key,value> re-rehash the process

Rehash under the concurrency

1) Suppose we have two threads. I marked it in red and light blue.

Let's look back at this detail in our transfer code:

1234567 do { &NBSP;&NBSP;&NBSP;&NBSP; entry< K,v> next = E.next; //<--assume that a thread is scheduled to be suspended when it is executed       int i = Indexfor (E.hash, newcapacity ); &NBSP;&NBSP;&NBSP;&NBSP; e.next = newtable[i]; &NBSP;&NBSP;&NBSP;&NBSP; newtable[i] = e; &NBSP;&NBSP;&NBSP;&NBSP; e = Next; } while (E! = Code class= "Java keyword" >null

And our thread two execution is done. So we have the following look.

Note that because Thread1 's e points to key (3), and next points to key (7), after thread two rehash, it points to the linked list of threads two reorganization. We can see that the order of the linked list is reversed.

2) The line Cheng is dispatched back to execute.

    • First executes newtalbe[i] = e;
    • Then E = Next, which led to the E pointing to Key (7),
    • The next loop, next = E.next, causes next to point to key (3).

3) All is well.

Line Cheng went on to work. Take the key (7) down, put it on the first one of Newtable[i], and move e and next down.

4) Ring link appears.

E.next = Newtable[i] Causes key (3). Next points to key (7)

Note: At this point the key (7). Next has pointed to key (3), and the ring list appears.

So, when our thread was called to Hashtable.get (7), the tragedy appeared--infinite Loop.

Summarize

When accessing a shared map in a multithreaded concurrency environment, be sure to use a thread-safe map container, such as concurrenthashmap,hashtable.

Java Fundamentals: Test, Analysis and summary of HASHMAP suspended animation lock problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.