Practical technical guides

Math.abs(hashCode()) % n Can Be Negative: Bucket Java Keys With floorMod

Measured on JDK 23: three strings hash to Integer.MIN_VALUE and break bucket indexes once the bucket count is not a power of two. Safe fixes.

By Sandeep Belgavi · Published 2026-12-06

A bucket index that is usually correct

Hash bucketing is everywhere in ordinary Java code: spread help-desk cases across worker queues, pick a shard for an order, choose a cache partition, assign a customer to an experiment arm. The one-line version almost always looks like this:

int bucket = Math.abs(key.hashCode()) % buckets;

It passes every test written with ordinary keys. It fails for one hash value out of about four billion, and because String.hashCode is deterministic, that value belongs to specific strings that will fail every time.

What the language guarantees

Two facts from the Java specification and the Math documentation combine here.

The remainder operator % in Java takes the sign of the dividend. -7 % 3 is -1, not 2. So key.hashCode() % buckets is negative for about half of all keys, which is why people add Math.abs in the first place.

Math.abs(int) cannot represent the absolute value of Integer.MIN_VALUE, because two's complement integers have one more negative value than positive values. The documentation states that if the argument equals Integer.MIN_VALUE, the result is that same value, which is negative. Since Java 15 there is also Math.absExact, which throws ArithmeticException instead of returning the negative value.

So Math.abs(h) % n is negative exactly when h == Integer.MIN_VALUE and n does not divide 2^31.

Measured on JDK 23

I ran a small program on JDK 23.0.2 with four keys. The last three are well known strings whose String.hashCode() is Integer.MIN_VALUE.

KeyhashCode()Math.abs(h) % 16h % 16Math.floorMod(h, 16)(h & 0x7fffffff) % 16
CASE-1001-8549711713-31313
polygenelubricants-21474836480000
GydZG_-21474836480000
DESIGNING WORKHOUSES-21474836480000

With 16 buckets the bug is invisible: -2147483648 % 16 is 0 because 16 divides 2^31. Every power-of-two bucket count hides it. Change the count to 10 and the same key gives Math.abs(h) % 10 = -8, which throws ArrayIndexOutOfBoundsException when used to index an array of queues, or silently creates a bucket with a negative id when used as a map key or a shard name. Math.floorMod(h, 10) gives 2, and the mask form gives 0. Math.absExact(h) throws "Overflow to represent absolute value of Integer.MIN_VALUE".

This is why the bug survives for years. Teams start with a power-of-two bucket count, everything works, and then someone resizes to 10 or 12 for capacity reasons and a fixed set of keys starts failing.

Two correct formulas, and they disagree

Both of these always return a value in 0..n-1 for positive n:

int a = Math.floorMod(key.hashCode(), n);          // mathematical modulo, sign of the divisor
int b = (key.hashCode() & 0x7fffffff) % n;         // clear the sign bit, then remainder

They are not the same function. For CASE-1001 with 16 buckets both give 13, but Math.abs(h) % 16 gave 3. For negative hashes, floorMod returns n - (|h| mod n) when the remainder is non-zero, while Math.abs(h) % n returns |h| mod n. Switching formulas therefore moves every key with a negative hash except those whose remainder is 0 or exactly n/2. With well-spread hashes about half of all keys are negative, but a key population with a shared prefix can be far from that: for the 2,000 ids CASE-1000 to CASE-2999 every hash was negative, and switching moved 1,600 of them with 10 buckets and 1,752 with 16. The mask form keeps the bucket for non-negative hashes and changes it for negative ones too, because clearing the sign bit is not the same as taking the absolute value.

That matters when the bucket is persistent: a shard that stores data, a partition with ordering guarantees, an experiment arm a customer has already seen. Fixing the formula is then a data migration, not a one-line change.

Fixing it in a live system

If the bucket is not persistent, for example worker queues that only need even load, change the formula and deploy.

If it is persistent, fix the failure without moving anyone:

static int legacyBucket(String key, int n) {
    int h = key.hashCode();
    int r = Math.abs(h) % n;          // the formula already in production
    return r >= 0 ? r : r + n;        // only Integer.MIN_VALUE reaches this branch
}

This keeps every existing assignment identical, because Math.abs(h) % n is non-negative for every hash except Integer.MIN_VALUE, and gives that one value a valid bucket. Document that the formula is legacy and frozen. New bucketing schemes should use Math.floorMod from the start.

Before shipping, check what the old code did with the failing keys. If it threw, no data was ever written for them and the new bucket is free to choose. If it produced a negative shard id that was used as a string, data may exist under a name like shard--8, and it needs to be moved explicitly.

Beyond the sign: is the bucket stable

The sign bug is one way bucketing goes wrong. Three related assumptions deserve a check while you are in the code:

  • hashCode stability across processes. String.hashCode is specified and stable. Many others are not: Object.hashCode is identity-based, enum and record hash codes depend on their components' hash codes, and a hashCode on a class you do not own may change between library versions. A bucket that must be the same in two services or across restarts should hash a canonical byte form with a specified function, not call hashCode.
  • Distribution. String.hashCode is a polynomial with multiplier 31. Keys with a common prefix and a short varying suffix, such as sequential case ids, map to consecutive hash values, and a power-of-two n then takes the low bits only. Check the bucket histogram for your real key population.
  • Resizing. Any hash mod n scheme moves most keys when n changes. If buckets will be resized, use consistent hashing or rendezvous hashing, which move only about 1/n of keys.

Other languages, same question

The same bug appears wherever the remainder takes the sign of the dividend. C, C++, C#, Go, JavaScript and Rust's % all behave like Java's, and each has the same asymmetry between the most negative integer and its absolute value. Python's % is a mathematical modulo with the sign of the divisor, so hash(key) % n is never negative in Python, which is one reason code ported from Python to Java picks up the bug. Python's built-in hash for strings is randomised per process unless PYTHONHASHSEED is fixed, so it is not suitable for persistent buckets either.

When two services in different languages must agree on a bucket, define the function in a language-neutral way: the bytes to hash (for example the UTF-8 encoding of the canonical key), the hash function (a specified one such as a fixed-seed 64-bit hash), and the reduction to a bucket. Then test both implementations against the same table of keys and expected buckets, including keys whose hash has the sign bit set.

Failure modes

  • Negative index for three specific customers. The same keys fail on every request, so the incident looks like bad data, not a bug in shared code.
  • Hidden by powers of two until a resize to a non-power-of-two count.
  • Formula fix moves most keys with a negative hash and breaks a persistent shard or experiment assignment.
  • Math.abs on a long hash has the same problem with Long.MIN_VALUE.
  • Hand-written hash of a composite key overflows into Integer.MIN_VALUE more often than random chance suggests when the combination is a plain sum or XOR of related values.

Verification

Put the three known Integer.MIN_VALUE strings into the unit tests of every bucketing function, with several bucket counts including 10, 12 and 16, and assert 0 <= bucket < n. For a migration, run old and new functions over a sample of real keys and count how many move; for the legacy-preserving fix that count must be zero except for keys whose hash is Integer.MIN_VALUE. The companion example has these tests in Python with a faithful port of String.hashCode, and a Java file you can run directly with java Buckets.java on JDK 15 or later, since it calls Math.absExact.

Primary references and authorship

Sources read December 6, 2026. Original explanations, measurements and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/java_bucket_floormod. Views are my own and do not represent any employer, past or present.