Search code examples
javahashcollision

Hash collisions in Java's ConcurrentHashMap: which precautions must be taken?


I'm having a bit of an issue understanding how hashes (or rather: hash collisions) are handled by Java's ConcurrentHashMap.

For example, when I'm running each:

"Ea".hashCode()
"FB".hashCode()

... I am presented with the same integer twice: 2236

Now, if instead I use each of these strings as a key in an instance of ConcurrentHashMap, there seem to be no issues.

ConcurrentHashMap<String, Object> testMap = new ConcurrentHashMap<>();
testMap.put("Ea", Math.random());
System.out.println(testMap.containsKey("FB"));

The last line returns false, despite a key with the same hash code value ("Ea") already being present in the map.

How does this work, and more importantly: what precautions do I need to take to prevent hash collisions in my instances of ConcurrentHashMap?


Solution

  • Javas ConcurrentHashMap uses a HashTable as the underlying data structure to store entries. The way this table deals with collisions is described here: How do HashTables deal with collisions?

    Generally you don't need to be concerned about hash collision when using the HashMap and ConcurrentHashMap types of the standard library. Those are guaranteed to not cause problems with keys that have the same hash values.