Java HashMap.get(Object) infinite loop

后端 未结 3 452
温柔的废话
温柔的废话 2021-02-03 23:23

A few answers on SO mention that the get method in a HashMap can fall into an infinite loop (e.g. this one or this one) if not synchronized properly (and usually the bottom line

3条回答
  •  野的像风
    2021-02-03 23:52

    You link is for the HashMap in Java 6. It was rewritten in Java 8. Prior to this rewrite an infinite loop on get(Object) was possible if there were two writing threads. I am not aware of a way the infinite loop on get can occur with a single writer.

    Specifically, the infinite loop occurs when there are two simultaneous calls to resize(int) which calls transfer:

     void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry e : table) {
             while(null != e) {
                 Entry next = e.next;
                 if (rehash) {
                     e.hash = null == e.key ? 0 : hash(e.key);
                 }
                 int i = indexFor(e.hash, newCapacity);
                 e.next = newTable[i];
                 newTable[i] = e;
                 e = next;
             }
         }
     }
    

    This logic reverses the ordering of the nodes in the hash bucket. Two simultaneous reversals can make a loop.

    Look at:

                 e.next = newTable[i];
                 newTable[i] = e;
    

    If two threads are processing the same node e, then first thread executes normally but the second thread sets e.next = e, because newTable[i] has already been set to e by the first thread. The node e now points to itself, and when get(Object) is called it enters an infinite loop.

    In Java 8, the resize maintains the node ordering so a loop cannot occur in this fashion. You can lose data though.

    The Iterators for LinkedHashMap class can get stuck in an infinite loop when there are multiple readers and no writers when access ordering is being maintained. With multiple readers and access order every read removes and then inserts the accessed node from a double linked list of nodes. Multiple readers can lead to the same node being reinserted more than once into the list, causing a loop. Again the class has been rewritten for Java 8 and I do not know if this issue still exists or not.

提交回复
热议问题