Practical technical guides / Core IT: Java and JVM (hash codes across runs)

Java hashCode Is Not Stable Across Runs: Enum and Identity Hashes Change Between JVMs, So Never Partition or Persist by Them

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.

By Sandeep Belgavi · Published 2026-11-20

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:

TypehashCode across runsWhy
Stringstablespecified as s[0]*31^(n-1) + ... + s[n-1]
Integer, Long, Booleanstablespecified from the value
List, Set, Map from the collections frameworkstable if the elements arespecified as combinations of element hashes
enum constantsnot stableEnum.hashCode is final and identity-based
Plain objects without an override, Class objectsnot stableidentity hash
Recordsnot stable in generalalgorithm 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:

ConditionHISTORY.hashCode()Partition by enum hashPartition by namePartition by CRC32
Identical run 11160460865140
Identical run 21160460865140
One earlier identity hash anywhere1247233941540
Five earlier identity hashes1325547227340
Computed on a new threadchanged between two runs of the same command1 in the recorded run40
-Xshare:off1599771323340
-Xint1160460865140

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 record ShelfKey(Shelf shelf, String isbn) all fold the enum's identity hash into their result, so they inherit the instability even though List.hashCode itself is specified.
  • Iteration order. A HashSet<Shelf> or HashMap<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. Use EnumSet and EnumMap, 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.hashCode is specified, so name().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 HashSet of 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.sh

It 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.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/java/hashcode_across_runs. Views are my own and do not represent any employer, past or present.