Scrivio Interview library
LeadershipPrincipal7 min read · updated 12 November 2026

Java 7u6 added an optional alternative String hashing for HashMap to resist collision attacks, and Java 8 removed it in favour of treeifying large bins (JEP 180). Other languages chose per-process randomized hashing. What does this decision show about how Java weighs compatibility, and how should it shape your own platform decisions?

It shows that Java treats published behaviour as a contract: String.hashCode() is specified in its Javadoc and stored or relied on in countless systems, and randomized hashing would have changed HashMap iteration order between runs, breaking code and tests that accidentally depended on it. So instead of changing hash values, Java 8 bounded the worst case inside HashMap by turning crowded bins into balanced trees (JEP 180), accepting more internal complexity to avoid breaking users. For our own platforms, the lesson is that anything users can observe becomes a contract, so we should make unspecified behaviour visibly unspecified early, as Set.of and Map.of do by randomizing their iteration order.

Why this question is asked

Hash flooding attacks became widely known around 2011: an attacker sends a request with thousands of parameters chosen to have the same hash code, every one lands in the same bucket, and parsing that request takes seconds of CPU. Every major language had to respond, and they responded differently. Interviewers ask senior engineers about Java's choice because it is a clean case study in trade-offs between security, compatibility and complexity, and because the same trade-off appears whenever we own a library or API that many teams depend on. In this answer, we will recap the attack, walk through Java's two responses and why the first was removed, compare it with randomized hashing, and draw out the rules for our own platform decisions.

1A Quick Recap of the Collision Attack

A HashMap is fast because keys spread across many buckets. If an attacker can choose keys that all have the same hash code, they all land in one bucket, and before Java 8 that bucket was a linked list. Inserting n such keys costs about n squared over two comparisons, so 50,000 crafted form fields turn a quick parse into billions of string comparisons.

String.hashCode() makes this easy, because its formula is published and simple: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]. "Aa" and "BB" have the same hash, 2112, and any string built from blocks of those two pairs collides with every other string of the same length built the same way. An attacker can generate millions of colliding keys offline.

2Java's First Response and Why It Was Removed

Java 7u6 added an optional alternative hashing for String keys in HashMap and related classes, enabled with a system property (jdk.map.althashing.threshold). Above the threshold, maps used a different, seeded hash function for strings, so attackers could not predict collisions.

It was optional and off by default precisely because of compatibility, and that made it of limited use: services had to know to turn it on. It also added a field and a code path to every map and changed iteration order when enabled. Java 8 removed it and replaced it with JEP 180: when a single bin grows past a threshold, 8 entries in a table of at least 64 bins, HashMap converts the bin into a balanced red-black tree. Lookups in that bin become O(log n) instead of O(n). Colliding String keys are Comparable, so the tree can order them with compareTo even though their hashes are equal, which bounds the attack for exactly the keys it targeted.

3Why Not Randomize Hashing Like Other Languages?

Several other runtimes chose per-process randomized hashing: every process picks a secret seed at start-up, and string hashes depend on it, so an attacker cannot precompute collisions. Java could not make that choice for String.hashCode() for two reasons.

First, String.hashCode() is specified. Its formula is written in the Javadoc, so programs are allowed to rely on it, and many do: hash values are persisted in files and databases, used to partition data across machines, compiled into switch statements on strings, and compared across JVMs. Changing the value would break data, not just code. Second, randomizing hashes would change HashMap's iteration order from one run to the next. HashMap has never promised an order, but a great deal of code and many tests accidentally depend on the order they happened to observe, such as a test that compares a toString() of a map with a fixed string. Those would start failing randomly.

Two ways to defend against hash flooding
AspectRandomized hashingTree bins (Java 8)
Hash valueschange per processunchanged, as specified
Iteration orderchanges between runsunchanged for normal maps
Attack costcollisions hard to predictcollisions possible, cost O(log n)
Complexityin the hash functionin HashMap's bin code
Who paysusers relying on order or valuesJDK maintainers
Java chose to keep observable behaviour and absorb the complexity internally.

4What the Trade-off Shows

The JDK accepted a considerably more complex HashMap, with tree nodes, conversion between lists and trees, and special handling for keys that are not Comparable, so that no user had to change anything. The complexity went to the small group of people who maintain the class, and the stability went to the millions who use it. That is a consistent pattern in Java's history: behaviour that has been observable for a long time is treated as fixed, even when it was never formally promised.

There is a cost to that pattern too. Tree bins only fully help with Comparable keys, and the iteration order users depended on is still not guaranteed, so the underlying fragility remains. Java later addressed that fragility differently for new APIs, which is the most useful lesson for us.

5Lessons for Our Own Platform Decisions

The first lesson is Hyrum's law in practice: with enough users, every observable behaviour of a system will be depended on by somebody, whatever the documentation says. So when we publish a library, API or service, we should assume that response field order, error message text, timing and iteration order will all become contracts unless we prevent it.

The second lesson is to make unspecified behaviour visibly unspecified from day one. The immutable collections from Set.of and Map.of, added in Java 9, randomize their iteration order with a seed chosen per JVM run. Nobody can depend on their order, because it changes every time the program starts, so tests that accidentally depended on it fail immediately in development rather than years later in a migration. We can apply the same idea: shuffle the order of unordered results in non-production environments, vary timing in tests, and avoid exposing internal identifiers that look stable.

The third lesson is to be careful what we specify. Writing the formula of String.hashCode() into the Javadoc made it permanent. When we document our own APIs, we should promise the minimum that users need, such as "returns the items in no particular order", and keep the freedom to change the rest. And when we must change behaviour, we follow Java's example: prefer an internal fix that keeps observable behaviour, and when that is impossible, give a long, loud deprecation period.

6Follow-up questions

Does the Java 8 change fully protect against hash flooding?

It bounds the cost for Comparable keys such as String, which were the main target, at O(log n) per operation. For keys that are not Comparable and share hash codes, a tree bin cannot order them and lookups can still degrade. Frameworks also limit the number of request parameters and headers, which is a cheaper first line of defence.

Why can Map.of randomize order when HashMap cannot?

Map.of was new in Java 9, so no code depended on its order yet. Randomizing from the first release meant the behaviour was never observed as stable. HashMap's order had been observable for nearly two decades, and changing it would have broken existing code.

How would you apply this when designing a REST API?

Document which fields and orderings are guaranteed, return unordered collections in an order that is not stable in test environments, and treat any change to observable behaviour, including error formats, as a versioned change. Contract tests with major consumers show which behaviours they actually rely on.

7Conclusion

In this answer, we saw that Java could not change String.hashCode() because its formula is specified and relied on widely, and could not randomize hashing because HashMap iteration order would change between runs and break code and tests that depended on it. Java 8 instead bounded the worst case with tree bins (JEP 180), keeping hash values and behaviour compatible at the cost of internal complexity. The lesson for our own platforms is that published behaviour becomes a contract, so we should promise little and make unspecified behaviour visibly unspecified early, as Set.of and Map.of do.

What to say in the interviewAbout 90 seconds aloud

Open with

This decision shows how seriously Java treats observable behaviour as a contract. String.hashCode has its formula written in the Javadoc, and people persist those values, partition data with them and compile string switches against them, so it cannot change.

Then, if they want more

Per-process randomized hashing, which some other runtimes adopted, would also have changed HashMap iteration order between runs. That order was never promised, but lots of code and tests depend on it by accident, and they would have started failing randomly. The optional alternative hashing in 7u6 was off by default for the same reason, so few used it.

Java 8 replaced it with JEP 180: crowded bins become red-black trees, so collisions cost log n instead of n, and since Strings are Comparable, the attack on String keys is bounded without changing any hash value or iteration order. The JDK took on more internal complexity so that users did not have to change anything.

For my own platform decisions, I take three things from it. Anything users can observe will become a contract, so I promise the minimum in docs. I make unspecified behaviour visibly unspecified early, the way Set.of and Map.of randomize iteration order per run, so nobody can depend on it.

And when I must fix something, I prefer an internal change that keeps observable behaviour.

About this answer

Last updated
12 November 2026
Versions it names
Java 8, Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Java 7u6 added an optional alternative String hashing for HashMap to resist collision...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/3b6326f4b3/