DeadLock in ConcurrentHashMap

The following code, when run, never ends or loops in an infinite loop.

I'm not sure where it gets stuck.

I wonder when I change AaAa

to AaAa

, everything works fine as expected.

 public class Test {

    public static void main(String[] args) {

        Map<String, Integer> map = new ConcurrentHashMap<>(16);
        map.computeIfAbsent(
                "AaAa",
                key -> {
                    return map.computeIfAbsent(
                            "BBBB",
                            key2 -> 42);
                }
        );
    }

}

      

Can someone help me understand this behavior.

+3


source to share


2 answers


"AaAa"

and "BBBB"

have the same hashCode()

- 2031744. Therefore, both keys are mapped to the same map file.



The outer one map.computeIfAbsent

locks this bit, and the inner one map.computeIfAbsent

tries to lock it before the lock is released - hence a dead end.

+10


source


Whenever two different objects have the same hash code, we call it collision

.

The collision is not important, it just means there is more than one object in the same bucket, so the search HashMap

has to look for the correct object again. Many collisions degrade system performance, but they do not produce incorrect results.

But if you take a hash code for a unique descriptor of the object, for example, use it as the key in Map

, then you sometimes get the wrong object .

There Java

are 4,294,967,296

compartments in ( 2^32

possible values int

). With 4 billion slots, collisions seem extremely unlikely, right? Because although collisions are rare, they are inevitable . For example, strings "Aa"

and "BB"

produce the same hashCode: 2112

. "AaAa"

and "BBBB"

have the same hashCode() - 2031744

and many others.



Objects that are equal must have the same hashcode in the current process

Please note that this does not mean the following common misconceptions:

  • Unequal objects must have different hash codes - WRONG !
  • Objects with the same hash code must be equal - WRONG !
0


source







All Articles