Quick revision
The short answer
A Java 21 service is much less exposed than a Java 7 one, but not immune. String.hashCode() is specified and predictable, so an attacker can easily generate thousands of keys with the same hash, yet since Java 8 the flooded bucket becomes a red-black tree and String is Comparable, so each lookup or insert stays O(log n) instead of O(n). The attack still costs CPU and memory for parsing and building the tree, so I would bind requests to typed objects where possible and limit body size, field count and nesting depth both in the JSON parser and at the gateway.
What to remember
In this answer, we saw that String.hashCode() is specified and predictable, so colliding field names are easy to generate, and that a JSON body parsed into a HashMap lets an attacker choose every key. Since Java 8, a flooded bin becomes a red-black tree, and because String is Comparable, lookups stay O(log n), so a Java 21 service is far less exposed than a Java 7 one. The attack still costs parsing time, CPU and memory, and custom non-Comparable keys are more exposed, so we bind to typed DTOs where possible and limit body size, field count and nesting depth in the parser and at the gateway.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A Java 21 service is much less exposed than a Java 7 one, but not immune. String.hashCode() is specified and predictable, so an attacker can easily generate thousands of keys with the same hash, yet since Java 8 the flooded bucket becomes a red-black tree and String is Comparable, so each lookup or insert stays O(log n) instead of O(n). The attack still costs CPU and memory for parsing and building the tree, so I would bind requests to typed objects where possible and limit body size, field count and nesting depth both in the JSON parser and at the gateway.
Why this question is asked
Hash flooding was presented publicly around 2011 as a cheap denial of service against many web platforms: one request with a few megabytes of carefully chosen keys could keep a server busy for minutes. It is a good interview question because the honest answer is nuanced. The JDK fixed the worst of it, but a security reviewer is still right to ask, and the remaining risk lives in the parser and the gateway rather than in HashMap. In this answer, we will recap how hash flooding works, show why String keys are easy to collide, see what changed in Java 8, measure what risk remains, and then set the limits I would put in place.
1A Quick Recap of Hash Flooding
A HashMap is fast because keys spread across many buckets, so each lookup checks only a node or two. Hash flooding is an attack that breaks that assumption on purpose. The attacker sends many keys that all have the same hash, so they all land in one bucket. In a map whose buckets are plain linked lists, inserting the n-th key means walking a chain of n - 1 keys, so inserting n keys costs about n squared over 2 comparisons. For 50,000 keys that is over a billion string comparisons from one request.
When a JSON body is parsed into a HashMap<String, Object>, every field name becomes a key. So the attacker controls the keys completely, which is exactly the situation the attack needs.
2Why String Keys Are Easy to Collide
String.hashCode() is specified in the Javadoc: it is s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]. Because the formula is public and has no secret seed, anyone can compute colliding strings offline. The classic building blocks are "Aa" and "BB", which have the same hash. Any string made of k such blocks collides with every other one, which gives 2^k colliding keys.
Notice that the attacker does not need to know anything about our service. The same payload works against any Java code that puts untrusted strings into a HashMap. That is why the JDK cannot simply change the formula: it is part of the String contract, and code depends on it.
3What Changed in Java 8
Java 7 update 6 briefly added an alternative, randomised string hashing for large maps behind a system property, and Java 8 replaced that with a structural defence (check the 7u release notes if the history matters to you). Since Java 8, when a bucket reaches 8 nodes in a table of at least 64 slots, HashMap converts it into a red-black tree. The tree orders nodes by hash first, and when hashes are equal, which is always the case in a flood, it uses compareTo if the keys are Comparable and of the same class. String is Comparable, so the tree can always choose a side, and lookups and inserts in the flooded bucket cost O(log n) comparisons.
For our 50,000 keys, that turns about a billion comparisons into roughly 50,000 times 16, under a million. A request that would have taken minutes now takes milliseconds of map work.
| n keys | List bucket (Java 7) | Tree bucket (Java 8+) |
|---|---|---|
| 1,000 | about 500,000 comparisons | about 10,000 |
| 10,000 | about 50 million | about 140,000 |
| 50,000 | about 1.25 billion | about 800,000 |
4What Risk Remains
The attack is reduced, not removed. Every key must still be parsed, allocated as a String, hashed and compared with compareTo, which for long keys sharing a long common prefix means comparing many characters each time. TreeNodes are about twice the size of normal nodes, so the map uses more memory. And the request still has to be read off the network. An attacker who cannot cause minutes of CPU can still make each request noticeably more expensive than a normal one, and multiply that by many connections.
There is a sharper risk for keys that are not Strings. If our code builds maps keyed by a custom type that is not Comparable, colliding keys inside a tree bin fall back to a tie-break order for insertion, and lookups may have to search both subtrees. If an attacker can control the fields that feed such a key's hashCode(), the flooded bin can be nearly as slow as a list again. Custom key types built from request data deserve more scrutiny than String keys.
5The Limits I Would Put in Place
The cheapest defence is not to build an untyped map at all. Binding the request to a typed DTO, a record with the fields we expect, means unknown field names are skipped or rejected and never stored as map keys. We keep Map<String, Object> only where the payload is genuinely free-form.
Where we parse untrusted JSON, we limit what the parser will accept. Jackson 2.15 and later has StreamReadConstraints, with limits on nesting depth, number length, string length and field-name length, and newer releases add document length and token count limits; the exact limits and defaults depend on the version, so check your Jackson release. We set them explicitly in a customizer rather than relying on defaults. Field count per object is not always a built-in limit, so for free-form maps we can enforce it in a custom deserializer or validation step.
- Gateway or load balancerbody size cap, rate limits per client
- Web server and codecsmax in-memory body size
- JSON parsernesting depth, name and string length, token count
- Bindingtyped DTOs instead of
Map<String, Object> - HashMaptree bins keep String collisions at
O(log n)
5 layers, from the top down. Step through them one at a time.
Notice that the limits sit at two layers. The gateway or load balancer rejects oversized bodies before they reach any Java code, which also protects services we forget about. The parser limits catch what gets through. On Spring Boot 4 with Jackson 3, the package and builder names change, so check the migration guide for the equivalent settings.
6Follow-up questions
Which limits does your JSON library expose for this?
For Jackson 2.15 and later, StreamReadConstraints covers maximum nesting depth, maximum number length, maximum string length and, from 2.16, maximum field-name length and document length, with a token-count limit added later; the defaults have changed between releases, so we set the values we want explicitly. Jackson also has a FAIL_ON_UNKNOWN_PROPERTIES feature for typed binding. Other libraries such as Gson have fewer built-in limits, which is another reason to cap the body size before parsing.
Would switching to ConcurrentHashMap or LinkedHashMap help?
Not with flooding. Both use the same String hash, and both also treeify crowded bins, so they behave about the same as HashMap. TreeMap avoids hashing entirely and gives O(log n) for every key, at a higher constant cost for normal traffic, so it is not worth it just for this.
How would we test that the limits work?
With an integration test that posts a generated body of, say, 100,000 colliding keys and another with nesting depth 1,000, and asserts that the service rejects them with a 400 or 413 quickly, within a time budget. Running the same payloads in a load test confirms that CPU stays flat.
7Conclusion
In this answer, we saw that String.hashCode() is specified and predictable, so colliding field names are easy to generate, and that a JSON body parsed into a HashMap lets an attacker choose every key. Since Java 8, a flooded bin becomes a red-black tree, and because String is Comparable, lookups stay O(log n), so a Java 21 service is far less exposed than a Java 7 one. The attack still costs parsing time, CPU and memory, and custom non-Comparable keys are more exposed, so we bind to typed DTOs where possible and limit body size, field count and nesting depth in the parser and at the gateway.
Open with
I would tell the reviewer the risk is real but much smaller than it used to be. String.hashCode is specified, with no random seed, so it is trivial to generate thousands of field names with the same hash: Aa and BB collide, and any combination of those blocks collides too.
Then, if they want more
Parsing a JSON body into a HashMap lets the attacker choose every key. On Java 7 that bucket was a linked list, so inserting n keys was quadratic, and one request could burn minutes of CPU.
Since Java 8, a bucket with 8 or more nodes in a table of at least 64 becomes a red-black tree, and because String is Comparable, the tree can order keys with equal hashes, so each operation is O(log n). That turns a billion comparisons into under a million for 50,000 keys.
The attack still costs CPU and memory for parsing, allocating strings and building TreeNodes, so it is reduced, not removed, and maps keyed by custom non-Comparable types are more exposed because tree lookups may search both subtrees.
So I would bind requests to typed DTOs instead of Map<String, Object> wherever the shape is known, set explicit Jackson StreamReadConstraints for nesting depth, name length and string length, enforce a field count where we keep free-form maps, and cap the body size at the gateway.
Then I would add a test that posts a colliding payload and asserts it is rejected quickly.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8, Java 7, Java 21, Spring Boot 4
- 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.
- Official documentation
- java.util.HashMap, API documentation, The Collections Framework, overview
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 "A public endpoint parses request JSON into a HashMap<String, Object>. A security review...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/0a0613fa72/