Skip to content

Path 1 · lesson 5 of 5

Foundation17 minJava 21 (OpenJDK 21.0.13, HotSpot) · Spring Boot 3.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 hashCode turns 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.

CauseWhat you seeFix
A weak hashCode puts many keys in few bucketsCPU time inside HashMap.getNode or TreeNode.find; lookups slow down as the map growsA hashCode that uses all the fields equals uses
The map grows by repeated resizingOccasional slow put calls and bursts of allocation while it fillsCreate it with the expected number of entries
Boxed keys and valuesTens of megabytes of heap per million entries, more frequent garbage collectionFewer entries, primitive arrays, or a specialised collection
Nothing ever removes entriesHeap that grows for days, then OutOfMemoryErrorA 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 output
1. 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
With a good hash code a lookup takes 163 ns. With 100 hash codes and a 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 output
2. 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 found
Sizing the map up front fills it in 37 ms against 51 ms, and avoids allocating and discarding 17 tables. The million entries hold 70 MB, about 73 bytes each, where an int 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"]
From a key to its entry. The cost is decided by how many keys share the bucket and whether they can be ordered.
  • 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 Comparable keys 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
One resize, the last of the 17 on the way to a million entries.
  1. A resize happens inside whichever put crosses the threshold. That caller waits for the whole move, which is why a growing map shows occasional slow writes.
  2. 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, or equals and hashCode generated 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 String keys benefit because String is Comparable.
  • 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. Use ConcurrentHashMap.

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.

src/main/java/com/example/pricing/PriceKey.javaJava
/** 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 hashCode combines both components. A version that used only currency would put every key into a handful of buckets.
  • Comparable costs a few lines and lets a tree bin stay fast if keys ever do collide.

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

SessionKey.java (incorrect)Java
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 bucket

Why 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 userId reaches the right bucket, but equals compares 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

SessionKey.java (corrected)Java
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 ConcurrentHashMap and 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 can go wrong

hashCode over fewer fields than equals
Symptom
Lookups slow down steadily as the map grows, with CPU time in HashMap.getNode and the key's equals.
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 hashCode differs 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$TreeNode instances mean buckets grew past 8 entries. With a good hash code a large map consists almost entirely of HashMap$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, getNode or the key's equals and compareTo is 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 hashCode makes every lookup a search.
  • Tree bins limit the damage of collisions, and need Comparable keys 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 int in 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