Java HashMap.get(Object) infinite loop

后端 未结 3 511
温柔的废话
温柔的废话 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-04 00:03

    Given that the only possibility I see for an infinite loop would be e.next = e within the get method:

    for (Entry e = table[indexFor(hash, table.length)]; e != null; e = e.next)
    

    And that could only happen in the transfer method during a resizing:

     do {
         Entry next = e.next;
         int i = indexFor(e.hash, newCapacity);
         e.next = newTable[i]; //here e.next could point on e if the table is modified by another thread
         newTable[i] = e;
         e = next;
     } while (e != null);
    

    If only one thread is modifying the Map, I believe it is quite impossible to have an infinite loop with just one thread. It was more obvious with the old implementation of get before the jdk 6 (or 5):

    public Object get(Object key) {
            Object k = maskNull(key);
            int hash = hash(k);
            int i = indexFor(hash, table.length);
            Entry e = table[i]; 
            while (true) {
                if (e == null)
                    return e;
                if (e.hash == hash && eq(k, e.key)) 
                    return e.value;
                e = e.next;
            }
        }
    

    Even then the case still seems pretty improbable except if there are a lot of collisions.

    P.S: I'd love to be proven wrong though!

提交回复
热议问题