Video in progress

Strong Middle 🧺 Collections

How do you tell that a HashMap is running much slower than expected, and how does hashCode quality affect that?

If a profiler shows HashMap.getNode/putVal or equals taking a lot of time, the cause is often a badly distributed hashCode: keys pile up in a few buckets, and a lookup walks a chain or tree instead of being O(1). Measure the hash distribution and fix hashCode.

📖 Answer

On one project a coordinate key looked like this:

record Cell(int x, int y) {
    @Override public int hashCode() { return x + y; }   // (1,2) and (2,1) are the same
}

On a 1000×1000 grid it produces only about 2,000 distinct hashes, so an average bucket holds 500 keys. Every put called equals thousands of times.

How to detect it:

  • in an async-profiler or JFR flame graph, HashMap.getNode, TreeNode.find and the key's equals stand out;
  • a small diagnostic: count the unique hashes in the set of keys and the most repeated one.
Map<Integer, Long> dist = keys.stream()
        .collect(Collectors.groupingBy(Object::hashCode, Collectors.counting()));
System.out.println(keys.size() + " kalit, " + dist.size() + " xil hash");

The fix is to keep the record's default hashCode, or to mix the fields like 31 * x + y. Other traps: heavy work inside hashCode (walking a big list every time), which you can cache like String does if the object is immutable; or a slow equals, where you should compare the cheap fields first.

HashMap picks the bucket using only the low bits of the hash. Spreading the high bits with hash ^ (hash >>> 16) helps a little, but nothing can separate identical hashes.