On JDK 23 a HashMap key changed after put made its entry unreachable by any key, a second put duplicated it, and a TreeMap lost an entry. Immutable keys and a test.
An entry that iteration shows and get cannot find
Hansini is debugging the order-status cache in the Belgavi's Book Store back office. The cache is a HashMap<OrderKey, String> keyed by customer and order number. Logging the map shows {Jenya#1002=pending}, yet status.get(key) returns null, containsKey returns false, and remove does nothing. The map is not corrupt in the sense of a broken data structure. The key changed after it was inserted.
HashMap decides where an entry lives from the key's hashCode() at the moment of put, and it finds the entry later by recomputing the hash of the key you pass and comparing with equals. If a field that equals and hashCode read changes while the key is in the map, the entry stays in the bucket for the old hash with a key that no longer equals anything you can construct. The java.util.Map documentation states the rule: great care must be exercised if mutable objects are used as map keys, and the behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. The measurements below show what "not specified" looks like in practice on JDK 23.0.2; the probe compiles with --release 17.
Measured: a mutated HashMap key
static final class OrderKey {
String customer; int orderNo;
OrderKey(String c, int n) { customer = c; orderNo = n; }
@Override public boolean equals(Object o) {
return o instanceof OrderKey k && k.orderNo == orderNo && k.customer.equals(customer);
}
@Override public int hashCode() { return Objects.hash(customer, orderNo); }
}
Map<OrderKey, String> status = new HashMap<>();
OrderKey key = new OrderKey("Jenya", 1001);
status.put(key, "pending");
key.orderNo = 1002; // the bug: the key changes while it is in the map| Call after the mutation | Result |
|---|---|
status.get(key) (same instance) | null |
status.containsKey(key) | false |
status.get(new OrderKey("Jenya", 1001)) | null |
status.get(new OrderKey("Jenya", 1002)) | null |
status.size() and printing the map | 1, {Jenya#1002=pending} |
status.remove(key) | null, size still 1 |
No key you can build reaches the entry. A lookup with the new values hashes to a different bucket. A lookup with the old values hashes to the right bucket, but HashMap stores each node's hash and compares it first, then calls equals against the stored key, which now holds 1002 and is not equal. The entry is unreachable but still counted and iterated, so a cache keyed this way leaks memory and serves stale data at the same time.
It gets worse on the next write. Putting the same, already mutated instance again creates a second entry: size becomes 2, and both entries' keys are the identical object. Reverting the field to 1001 makes the first entry reachable again and strands the second. A helper that walks entrySet() and checks that map.get(e.getKey()) returns that entry's own value reports one unreachable entry in each of these states; this is the check worth putting in tests.
HashSet and TreeMap fail differently
A HashSet is a HashMap underneath, so the same mechanics give a set that contains two elements equal to each other. In the probe, an element added as 2001 and mutated to 2002 lets add(new OrderKey("Geetha", 2002)) return true; the set's size is 2 and elements.get(0).equals(elements.get(1)) is true. Code that relies on a set for deduplication now double-counts.
A TreeMap does not hash; it walks a red-black tree by comparing keys. Mutating a key breaks the ordering the tree was built on. With keys 10, 20 and 30 ordered by order number and 20 changed to 35, iteration returns 10, 35, 30, out of order. get for 35 happens to succeed, because the search path still reaches that node, while get for 30 returns null, because the search goes left of 35 and never reaches 30. Which lookups fail depends on the tree's shape, which is the practical meaning of "not specified".
Records do not save you from mutable components
A Java record generates equals and hashCode from its components. A record Basket(List<String> isbns) holding an ArrayList hashes by the list's contents, so adding an ISBN to the caller's list after the basket is a map key makes the entry unreachable exactly as above. The probe measures get returning null and one unreachable entry.
The fix belongs in the canonical constructor:
record FrozenBasket(List<String> isbns) {
FrozenBasket { isbns = List.copyOf(isbns); } // unmodifiable copy; caller changes do not leak in
}List.copyOf returns an unmodifiable list, so later changes to the caller's list do not affect the key, and frozen.isbns().add(...) throws UnsupportedOperationException. The probe confirms both, with no unreachable entries.
Fixes, in order of preference
- Make keys immutable. Final fields, defensive copies of collections and arrays, no setters. A record with immutable component types is the shortest correct form.
- Key by an identifier, not by the object. If the domain object must be mutable, key the map by its stable identifier (the order number alone, or a database id) instead of the object.
- Remove, change, put. When a key must change, take the entry out first:
String v = map.remove(k); k.orderNo = 3002; map.put(k, v);. The probe shows the entry reachable under the new value with nothing stranded. This only works if every holder of the key follows the protocol. - Identity semantics, deliberately. If you really mean "this object", use an
IdentityHashMap, which compares with==andSystem.identityHashCode, and accept that two equal keys are different entries.
ConcurrentHashMap does not change any of this: it makes concurrent access safe, not mutable keys.
Finding it in an existing codebase
- Search for classes used as map keys or set elements whose
equalsandhashCoderead non-final fields. Static analysis tools flag some of these; a review of everyMap<X, ...>where X has setters finds the rest. - In tests and debug builds, run the reachability check over long-lived maps after each operation that might mutate domain objects.
- Treat a growing map size with flat hit rates as a symptom: unreachable entries accumulate.
- Look for
equalsandhashCodegenerated by an IDE years ago on classes that have since gained setters.
A reachability check you can put in tests
The probe's helper is short enough to copy into a test utility. It walks the entries and asks the map to find each one by its own key:
static <K, V> int unreachableEntries(Map<K, V> map) {
int lost = 0;
for (Map.Entry<K, V> e : new ArrayList<>(map.entrySet()))
if (!map.containsKey(e.getKey()) || map.get(e.getKey()) != e.getValue()) lost++;
return lost;
}Comparing values by identity, not equals, is what catches the duplicate-entry case: after the second put, both entries have the same key object, containsKey is true for both, and only the value comparison shows that one of them can never be returned. Call it in tests after operations that update domain objects held as keys, and in a debug endpoint for long-lived caches. It is linear in the map's size, so keep it out of hot paths.
Failure modes in production
- A cache keyed by a request object that a later filter normalizes in place.
- A
Setused to deduplicate events whose objects are enriched after insertion. - Sorting keys in a
TreeMapby a mutable priority that the application updates. - A record key with an array component: arrays use identity for
equalsandhashCode, so record equality for arrays is identity, a different but related surprise.
Verification
The companion probe runs every case above and prints one line per observation; run.sh compiles with --release 17 and compares the output with the JDK 23 recording. The results do not depend on the operating system: they follow from how HashMap, HashSet and TreeMap store and search keys.
Limits
Exactly which lookups fail after a mutation depends on hash values, table size and tree shape; the probe shows one set of synthetic keys. The rule that holds everywhere is the documented one: do not change a key's equality while it is in a hashed or sorted collection.