Video in progress

What problem does converting HashMap buckets to trees in Java 8 solve?

In a bucket with many collisions, lookup drops from O(n) to O(log n). When a chain grows past 8 elements and the table is at least 64 long, the linked list turns into a red-black tree (TreeNode); if it shrinks below 6, it goes back to a list.

📖 Answer

Up to Java 7, all entries in one bucket sat in a plain linked list. If an attacker sent thousands of keys with the same hash (HTTP parameter names, for example), the server walked a long list on every request and CPU went to 100%. That is a "hash flooding" attack.

Since Java 8:

  • TREEIFY_THRESHOLD = 8: when a bucket has more than 8 entries, it is converted to a tree;
  • MIN_TREEIFY_CAPACITY = 64: if the table is small, it is resized first instead of building a tree;
  • UNTREEIFY_THRESHOLD = 6: if it shrinks after a resize, it goes back to a list.

How is order decided inside the tree? By hash first. If the hashes are equal and the key is Comparable, by compareTo. Otherwise it breaks the tie with the class name and System.identityHashCode, and lookup is still slower in that case.

The practical takeaway: making your own key classes Comparable can sometimes keep things working even with a bad hash. But the main thing is a good hashCode. With normal data, treeification almost never happens, because the chance of 8 elements landing in one bucket is very small.