Path 1 · lesson 5 of 5
HashMap with a million entries
A HashMap is fast only while keys spread evenly over its buckets. A weak hashCode, repeated resizing, boxed keys and keys that change after insertion each make a large map slow in a different way.
What you will learn
- Describe how a HashMap turns a key into a bucket and what it does when two keys share one
- Explain why a weak
hashCodeturns constant-time lookups into searches, and what tree bins change - Calculate when a map resizes and size it up front for a known number of entries
- Estimate the heap a large map of boxed keys and values holds
- Recognise an entry lost because its key changed after insertion
Before you start
The concept
A HashMap keeps an array of buckets. To store a key it calls hashCode(), turns the number into an array index, and puts the entry in that bucket. To find a key it computes the same index and looks only there. That is why a lookup takes about the same time in a map of ten entries and a map of a million.
The promise holds only while each bucket has very few entries. When many keys land in the same bucket, a collision, the map has to search inside the bucket, comparing keys one by one with equals(). The map still returns right answers. It just stops being fast.
When a large map degrades, the cause is nearly always one of four things, and they call for different fixes.
| Cause | What you see | Fix |
|---|---|---|
A weak hashCode puts many keys in few buckets | CPU time inside HashMap.getNode or TreeNode.find; lookups slow down as the map grows | A hashCode that uses all the fields equals uses |
| The map grows by repeated resizing | Occasional slow put calls and bursts of allocation while it fills | Create it with the expected number of entries |
| Boxed keys and values | Tens of megabytes of heap per million entries, more frequent garbage collection | Fewer entries, primitive arrays, or a specialised collection |
| Nothing ever removes entries | Heap that grows for days, then OutOfMemoryError | A bounded cache with eviction |
Why it exists
Maps are where in-memory state collects: caches, session stores, lookup tables loaded at startup, deduplication sets. They are written when the data is small and nobody revisits them as it grows. A key class with a careless hashCode costs nothing at a thousand entries and seconds at a million.
A map is also the most common shape of a memory leak in Java. An entry that is never removed is reachable for as long as the map is, and a map held in a singleton lives for as long as the process.
How it works inside
The index is computed from the hash code by mixing its high bits into its low bits and keeping as many low bits as the table needs: (h ^ (h >>> 16)) & (length - 1). The table length is always a power of two, starting at 16.
Inside a bucket, entries form a linked list. Since Java 8, a bucket that reaches 8 entries is converted into a balanced tree, a tree bin, once the table has at least 64 buckets. A tree bin can find a key in a number of steps that grows with the logarithm of the bucket size, but only if it can order the keys. It orders by hash code first and, for equal hash codes, by compareTo when the key class implements Comparable.
The program extras/HashMapAtScale.java stores 200,000 keys three times. The first key class has an ordinary hashCode. The other two return only 100 distinct hash codes, so each bucket in use holds about 2,000 keys. One of them is Comparable and one is not.
Program outputjava -XX:ActiveProcessorCount=2 -Xmx1g HashMapAtScale.java (part 1)
Real JVM output1. 200,000 keys, 100 distinct hash codes for the weak keys good hashCode put 32 ms in total get 163 ns each weak hashCode, Comparable key put 76 ms in total get 364 ns each weak hashCode, not Comparable put 5,407 ms in total get 9,926 ns each
Comparable key it takes 364 ns: the tree bins search 2,000 keys in about 11 comparisons. With the same weak hash code and a key that is not Comparable, it takes 9,926 ns, about 60 times the first row, and filling the map takes 5,407 ms against 32 ms. The tree cannot order those keys, so it has to search both sides.Resizing. A map resizes when its size exceeds capacity times the load factor, 0.75 by default. It allocates a table twice as long and moves every entry. A map created with new HashMap<>() and filled to a million entries does this 17 times. Memory. Each entry is a node object holding the hash, the key, the value and a link, and an Integer key or value is an object of its own.
Program outputThe same run (parts 2 and 3)
Real JVM output2. 1,000,000 Integer -> Integer entries
new HashMap<>() : 51 ms to fill, table doubled 17 times (16 -> 2,097,152 buckets)
HashMap.newHashMap(1,000,000): 37 ms to fill, table allocated once
heap held by the first map : 70 MB, about 73 bytes per entry
an int[1,000,000] for comparison : 3 MB
3. A key that changes after it was inserted
get(the same key object) : null
get(new MutableKey("user-1")): null
size() : 1 <- the entry is still held and can no longer be foundint array of the same length takes 3 MB. In part 3 the key's field is changed after insertion: the entry is still in the map, size() is 1, and neither the changed key nor a fresh copy of the original can find it.Architecture
Drawing diagram…
A flowchart. A key's hashCode is mixed and reduced to an index into the table. The index leads to a bucket. A bucket with one entry is found at once, a bucket with a few entries is a linked list compared with equals, and a bucket with eight or more entries is a tree bin. In a tree bin, Comparable keys allow an ordered search of about log n steps, and keys that are not Comparable may require searching both sides, up to n steps.
flowchart TD
K["key"] --> H["hashCode()"]
H --> M["mix high bits, keep low bits"]
M --> I["index into the table"]
I --> B0["bucket with one entry: found at once"]
I --> B1["bucket with a few entries: linked list, compare with equals()"]
I --> B2["bucket with 8 or more: tree bin"]
B2 --> C{"keys Comparable?"}
C -->|"yes"| F["ordered search, about log n steps"]
C -->|"no"| S["may search both sides, up to n steps"]- Everything before the bucket is arithmetic on one number and takes the same time for any map size. All of the variable cost is inside the bucket.
- Tree bins are a safety net for bad hash codes, not a replacement for a good one. They need
Comparablekeys to work well, and each tree node is about twice the size of a list node.
Step by step
Drawing diagram…
A sequence diagram. A request thread calls put. The map notices that its size is above 786,432, allocates a new table of 2,097,152 buckets, reads every entry of the old table of 1,048,576 buckets and places each in the new table at the same index or at the index plus the old length. Put returns. The old table is garbage of 4 megabytes, and this one put paid for moving 786,433 entries.
sequenceDiagram
participant T as Request thread
participant M as HashMap
participant O as Old table, 1,048,576 buckets
participant N as New table, 2,097,152 buckets
T->>M: put(key, value)
M->>M: size is now above 786,432
M->>N: allocate
M->>O: read every entry
M->>N: place each in the same index or index plus old length
M-->>T: put returns
Note over O: garbage, 4 MB
Note over T: this one put paid for moving 786,433 entries- A resize happens inside whichever
putcrosses the threshold. That caller waits for the whole move, which is why a growing map shows occasional slow writes. - The threshold is 0.75 times 1,048,576. With 4-byte references the old table is 4 MB that becomes garbage at once, and the new one is 8 MB.
In a real system
- Keys built by a tool are usually fine. A
record, orequalsandhashCodegenerated by the IDE from the same fields, spreads well. Trouble comes from hand-written versions that use one field, a constant, or a field with few distinct values. - Keys from outside can be chosen to collide. If the keys of a map come from request parameters or JSON, a caller can send thousands with the same hash code. Tree bins were added to Java 8 to limit the damage, and
Stringkeys benefit becauseStringisComparable. - A HashMap never shrinks. Removing entries, or calling
clear(), keeps the table at its largest size. A map that once held a million entries holds an 8 MB table until the map itself is released. - It is not safe for concurrent use. Two threads writing without a lock can lose entries and leave
size()wrong, and it fails without an exception. UseConcurrentHashMap.
When the real problem is that the map holds a million entries at all, no tuning of the map helps. A cache needs a size limit and an eviction rule, and a lookup table that large may belong in a database or a purpose-built store.
Java and Spring Boot
A key class and a lookup table for a Spring Boot 3.x service, written so that the four causes above cannot occur.
/** Immutable, with equals and hashCode over both components. */public record PriceKey(String sku, String currency) implements Comparable<PriceKey> { private static final Comparator<PriceKey> ORDER = Comparator.comparing(PriceKey::sku).thenComparing(PriceKey::currency); @Override public int compareTo(PriceKey other) { return ORDER.compare(this, other); }}Why it is written this way
- A record's fields are final, so the key cannot change while it is in a map.
- The generated
hashCodecombines both components. A version that used onlycurrencywould put every key into a handful of buckets. Comparablecosts a few lines and lets a tree bin stay fast if keys ever do collide.
@Componentclass PriceTable { private volatile Map<PriceKey, Long> pricesInCents = Map.of(); /** Called by the loader with the full set: build aside, then swap. */ void replace(List<PriceRow> rows) { Map<PriceKey, Long> next = HashMap.newHashMap(rows.size()); for (PriceRow row : rows) next.put(new PriceKey(row.sku(), row.currency()), row.cents()); pricesInCents = Map.copyOf(next); } Long priceOf(String sku, String currency) { return pricesInCents.get(new PriceKey(sku, currency)); }}Why it is written this way
HashMap.newHashMap(rows.size())allocates the table once at the right size.- The map is built on one thread and published as an immutable copy through a
volatilefield, so request threads never see a map that is being written. - The table is replaced as a whole. Nothing accumulates, so it cannot grow without limit.
Wrong, then right
A session key whose identity changes while it is in the map. The incorrect version is the one from part 3 of the lab.
Incorrect implementation
final class SessionKey { String userId; // changes when accounts are merged SessionKey(String userId) { this.userId = userId; } @Override public boolean equals(Object o) { return o instanceof SessionKey k && k.userId.equals(userId); } @Override public int hashCode() { return userId.hashCode(); }}sessions.put(key, session);key.userId = mergedId; // the entry is now in the wrong bucketWhy it is written this way
- The class is correct as a value. It is unsafe as a key, because the field that decides the bucket can be reassigned.
Why it fails
- The entry sits in the bucket chosen by the hash code of the old
userId. After the change, a lookup with the same object computes a different bucket and finds nothing. - A lookup with a new key for the old
userIdreaches the right bucket, butequalscompares against the changed field and fails. The entry is unreachable by any key and stays in the map until it is cleared: a leak of one session per merge.
Corrected implementation
record SessionKey(String userId) {}// to change the key: remove under the old key, put under the new oneSession session = sessions.remove(new SessionKey(oldId));if (session != null) sessions.put(new SessionKey(mergedId), session);Why it is written this way
- An immutable key cannot move. Re-keying is an explicit remove and put, which keeps the entry reachable at every moment.
Trade-offs
- Re-keying is two operations. Another thread can observe the moment between them, so a shared map needs
ConcurrentHashMapand a design that tolerates a brief miss. - Immutable keys mean allocating a new key object for a lookup. The JIT usually removes that allocation, and it is a small price compared with a lost entry.
Hands-on exercise
Measure the three key classes yourself
Reproduce the measurements, then see how much of the damage a better hashCode undoes.
Steps · 0 of 4 done
What you should see
With the last four characters each bucket holds about 20 keys and the third row drops to within a few times the first: 465 ns against 195 ns when this was written. The first four characters change nothing, because every id starts with one of the same 100 prefixes. More characters help only if they differ between keys.
What can go wrong
hashCode over fewer fields than equals
- Symptom
- Lookups slow down steadily as the map grows, with CPU time in
HashMap.getNodeand the key'sequals. - Cause
- Keys that differ only in the ignored fields share a hash code and therefore a bucket.
- Fix
- Generate both methods from the same fields, or use a record.
equals overridden without hashCode
- Symptom
map.get(new Key(...))returns null for a key that was certainly put.- Cause
- The default
hashCodediffers per object, so two equal keys look in different buckets. - Fix
- Always override both. Equal objects must return the same hash code.
A map used as a cache with no limit
- Symptom
- Heap after each full collection rises for days and ends in
OutOfMemoryError. - Cause
- Entries are added per user, request or message, and nothing removes them.
- Fix
- Use a cache with a maximum size and expiry, and check the entry count in a heap histogram.
How to troubleshoot
Suspected heavy collisions in a large map
Check
jcmd <pid> GC.class_histogram | grep HashMap
- How to read it
- Many
java.util.HashMap$TreeNodeinstances mean buckets grew past 8 entries. With a good hash code a large map consists almost entirely ofHashMap$Node.
CPU is high in code that only reads a map
Check
A CPU profile from JFR or async-profiler, filtered to HashMap frames
- How to read it
- Time in
TreeNode.find,getNodeor the key'sequalsandcompareTois time spent searching inside buckets.
Heap grows and a map is the suspect
Check
Two class histograms some minutes apart, comparing the HashMap$Node count
- How to read it
- A node count that only ever rises is a map without eviction. A heap dump then shows which map holds them.
Key takeaways
- A HashMap is fast only while keys spread over the buckets. A weak
hashCodemakes every lookup a search. - Tree bins limit the damage of collisions, and need
Comparablekeys to do it well. - Size a large map up front with
HashMap.newHashMap(n). Growing to a million entries from the default takes 17 resizes. - Boxed entries are expensive: about 73 bytes each in the lab, against 4 bytes for an
intin an array. - Keys must not change while they are in a map. Use records or other immutable types.
Practical check
Small scenarios, one decision each. Pick what you would do, then read why.
Scenario 1 of 2
A map of 1.2 million TenantKey(tenantId, resourceId) entries has become slow. The class has a hand-written hashCode that returns tenantId.hashCode(). There are 40 tenants. TenantKey does not implement Comparable.
What explains the slowdown best?
Scenario 2 of 2
A service loads 3 million product ids and prices into new HashMap<Long, Long>() at startup. The load takes longer than expected and the heap graph shows a staircase of allocations while it runs.
Which single change addresses both observations?
References
References: Java SE 21 API: HashMap (capacity, load factor, rehashing, tree bins and Comparable keys, not synchronized, newHashMap) ↗ · JEP 180: Handle Frequent HashMap Collisions with Balanced Trees ↗ · Java SE 21 API: Object.hashCode (the contract between equals and hashCode) ↗ · Report a problem