Video in progress
How are entries redistributed when a HashMap resizes, and why is the table length always a power of 2?
A power of 2 lets you compute the index quickly with (n - 1) & hash. When the table doubles on resize, each entry either stays at its index or moves to index + oldCapacity. This is decided by one new bit of the hash, so there is no need to recompute hashes.
📖 Answer
With n = 16, n - 1 = 0b1111, so the index is the low 4 bits of the hash. With n = 32 it is the low 5 bits. So to know the new index, it is enough to look at the 5th bit:
// the idea inside the JDK
if ((hash & oldCap) == 0) {
// "lo" list: the index doesn't change
} else {
// "hi" list: index + oldCap
}
Since Java 8, when a bucket is split in two, the relative order of its elements is preserved. In Java 7, a chain was moved in reverse order, and when two threads resized at the same time, the chain could turn into a cycle and get would fall into an infinite loop. That is the famous "HashMap 100% CPU" case. Java 8 fixed this particular cycle, but HashMap is still not thread-safe: entries can be lost and size can be wrong.
One more consequence: if you pass new HashMap<>(100) to the constructor, tableSizeFor rounds it up to 128 inside.
How it shows up on prod: when a big map is filled all at once, latency "jumps" during a resize, since the old and new arrays live together and every entry is walked. If you know the size, giving the capacity up front removes this.
Sign up to mark studied questions and save your progress.