Two identical JVM runs gave an enum the same hashCode; one earlier identity hash moved it to another partition. Partition by name or a byte hash instead.
Orders for one shelf landed on different partitions
Geetha's team at Belgavi's Book Store moved order events onto a topic with eight partitions. To keep each shelf's events in order, the producer picked the partition from the shelf, an enum: Math.floorMod(shelf.hashCode(), 8). In testing, HISTORY orders always went to partition 1. In production, with three producer instances, HISTORY orders went to partitions 1, 5 and 3, depending on which instance sent them, and the consumer that assumed per-shelf ordering started applying stock changes out of order.
Nobody had changed the enum. Each JVM computed a different hashCode() for the same constant, and that is allowed. This guide shows exactly what moves the value, what does not, and which keys are safe to partition or persist by.
What the contract promises
The Object.hashCode contract in the JDK 23 documentation says the value must be consistent during one execution while the object's equality information is unchanged, and then: "This integer need not remain consistent from one execution of an application to another execution of the same application."
Some classes override that with a stronger promise:
| Type | hashCode across runs | Why |
|---|---|---|
String | stable | specified as s[0]*31^(n-1) + ... + s[n-1] |
Integer, Long, Boolean | stable | specified from the value |
List, Set, Map from the collections framework | stable if the elements are | specified as combinations of element hashes |
enum constants | not stable | Enum.hashCode is final and identity-based |
Plain objects without an override, Class objects | not stable | identity hash |
| Records | not stable in general | algorithm unspecified, and an enum component makes it identity-based |
Enum.hashCode is declared final, so no enum can fix it by overriding. In JDK 23 its implementation computes System.identityHashCode(this) on first use and caches it in a field; the value is an identity hash.
Why it looks stable when you test it
Here is the trap. Run a small program twice on the same JDK and machine, and the enum's hash is usually identical both times. HotSpot generates identity hashes from per-thread pseudo-random state, and for an identical execution path that state evolves identically. The companion example recorded this on JDK 23.0.2:
| Condition | HISTORY.hashCode() | Partition by enum hash | Partition by name | Partition by CRC32 |
|---|---|---|---|---|
| Identical run 1 | 1160460865 | 1 | 4 | 0 |
| Identical run 2 | 1160460865 | 1 | 4 | 0 |
| One earlier identity hash anywhere | 1247233941 | 5 | 4 | 0 |
| Five earlier identity hashes | 1325547227 | 3 | 4 | 0 |
| Computed on a new thread | changed between two runs of the same command | 1 in the recorded run | 4 | 0 |
-Xshare:off | 1599771323 | 3 | 4 | 0 |
-Xint | 1160460865 | 1 | 4 | 0 |
One unrelated new Object().hashCode() earlier in the program moves the enum to a different partition. So does turning off class data sharing, which changes what runs during startup. On a new thread the value even differed between two runs of the identical command: 1075387855 in one, 71167697 in the next. A production service computes identity hashes all the time (in logging, in collections of objects without overrides, in libraries), so the sequence before your first shelf.hashCode() call depends on traffic, timing and thread scheduling. Three producer instances will disagree.
Unit tests rarely catch this, because a test computes the hash in the same order every time and gets the same number.
The probe
enum Shelf { FICTION, HISTORY, SCIENCE }
static int byEnumHashCode(Shelf s) { return Math.floorMod(s.hashCode(), PARTITIONS); }
static int byName(Shelf s) { return Math.floorMod(s.name().hashCode(), PARTITIONS); }
static int byCrc32(String key) {
CRC32 crc = new CRC32();
crc.update(key.getBytes(StandardCharsets.UTF_8));
return (int) (crc.getValue() % PARTITIONS);
}The run.sh script runs this seven ways and checks three properties rather than exact values, because identity hashes differ between JDK builds and machines: identical runs agree, the enum-hash partition moves under at least one condition, and the name and CRC32 partitions never move.
Where it bites
Anywhere a hash leaves the JVM that computed it or must agree between JVMs:
- Partitioning. Kafka producers, custom shard routers, consistent-hash rings. Each instance computes its own value.
- Persisted keys. A cache key, file name or database column derived from
hashCode()of an enum, a record with an enum component, or an object without an override is wrong after restart. - Composite hashes.
Objects.hash(shelf, isbn),List.of(shelf).hashCode()and a recordShelfKey(Shelf shelf, String isbn)all fold the enum's identity hash into their result, so they inherit the instability even thoughList.hashCodeitself is specified. - Iteration order. A
HashSet<Shelf>orHashMap<Shelf, V>can iterate in a different order in each JVM. Output that depends on it (reports, test snapshots, the order of tool descriptions sent to a model) changes between runs. UseEnumSetandEnumMap, which iterate in declaration order. - Distributed frameworks. Any engine that hashes keys in one process and expects the same result in another has the same problem, which is why such engines warn against keys without a well-defined hashCode.
What to use instead
Derive the key from data whose bytes are specified and stable:
shelf.name()and hash the string, or better, a fixed byte hash of it.String.hashCodeis specified, soname().hashCode()is stable across runs and JDK versions.- A stable code you control, such as a field
shelf.code()that never changes when constants are reordered or renamed. Ordinal is stable across runs but changes when someone inserts a constant in the middle. - A byte-level hash (CRC32, Murmur3, SHA-256 truncated) of a canonical encoding of the key, if other languages also need to compute the partition. The producer and every consumer in every language must agree on the encoding.
- For Kafka specifically, send a key as bytes (for example the shelf name in UTF-8) and let the default partitioner hash the bytes. Do not override partitioning with
hashCode().
Renaming an enum constant changes name(), so a name-based key is a schema: treat renames as migrations.
Failure modes
- Works in tests, fails with more than one instance. The most common shape of this bug.
- Silent reordering. Messages for one key spread across partitions; consumers see them out of order with no error.
- Cache misses after deploy. A persisted key derived from an identity hash never matches again after restart, so the cache silently becomes useless, or worse, collides with other keys.
- Snapshot tests that flip. Output ordered by a
HashSetof enums or objects changes when unrelated code is added.
Tradeoffs
Identity-based hashing is fast and needs no knowledge of the object's fields, which is why the JVM uses it. String.hashCode is cheap and stable but weak against crafted inputs and Java-specific; a standard byte hash costs a little more and is portable. A dedicated stable code is the most robust option and the most work, because every new constant needs one. For partitioning and persistence the extra work is worth it; for in-memory maps inside one JVM, hashCode() is exactly right.
Verification
Search for hashCode() and Objects.hash in partitioners, routers, cache-key builders and anything written to disk or the network, and check every type involved against the table above. Then test across JVMs, not within one: run the key computation in two processes with different warm-up (the example uses one extra identity hash) and assert identical results. The companion script does this in a few seconds.
For an existing topic or cache, check the data as well as the code. Group recent messages by their business key and count distinct partitions per key; any key that appears on more than one partition was routed by something unstable, or the partition count changed. For a persisted cache, compare the hit rate in the hour before and after a deploy. A key derived from an identity hash shows a hit rate that collapses at every restart and slowly recovers, a pattern that is easy to misread as a cold-cache effect.
Running the companion code
cd examples/java/hashcode_across_runs
sh run.shIt needs JDK 17 or newer and a POSIX shell. recorded-jdk23.txt holds the JDK 23.0.2 run on Windows 11 that the tables above come from.