Subtraction comparators overflow on ordinary timestamps and break transitivity. What the contract requires, what sorting and TreeSet then do, and a measured run.
A comparator that looks finished
Subtraction comparators are short, they pass a quick test, and they keep turning up in code review:
Comparator<Order> byCreated = (a, b) -> (int) (a.createdAtMillis() - b.createdAtMillis());
Comparator<Order> byAdjustment = (a, b) -> a.adjustmentPaise() - b.adjustmentPaise();Both are wrong for ordinary data, and the first one is wrong for data you probably have today. A difference of two epoch-millisecond timestamps is a long. Casting it to int keeps the low 32 bits. Any two timestamps more than 2^31 milliseconds apart, about 24.8 days, can come out with the wrong sign. The second comparator overflows when its operands have opposite signs and large magnitudes, which happens with sentinel values such as Integer.MIN_VALUE for an unknown amount.
This guide measures what happens next, on synthetic book orders from the fictional Belgavi's Book Store, with JDK 23.0.2. The point is not that overflow exists. It is what a broken comparator does to the collections and sorts that depend on it, and why some of those failures are silent.
What the contract requires
The java.util.Comparator documentation for Java SE 25 states three requirements. The sign must be antisymmetric: signum(compare(x, y)) == -signum(compare(y, x)) for all x and y. The relation must be transitive: if compare(x, y) > 0 and compare(y, z) > 0, then compare(x, z) > 0. And compare(x, y) == 0 must imply that x and y compare the same way against every z.
There is also a fourth property, consistency with equals, which the documentation describes as generally the case but not strictly required: compare(x, y) == 0 should have the same boolean value as x.equals(y). Sorted sets and maps care a great deal about it, as shown below.
Measured violations
The companion example builds five orders. ORD-1001 is at a fixed synthetic origin. ORD-1002 is 10 days later. ORD-1003 and ORD-1004 share a timestamp 30 days after the origin. ORD-1005 is 60 days after it. Their adjustments include 25,000, -25,000, Integer.MAX_VALUE and Integer.MIN_VALUE + 1.
The truncating comparator says ORD-1001, created 30 days before ORD-1003, compares as later: compare returns 1702967296, a positive number. Sorting the five orders with it gives ORD-1001, ORD-1002, ORD-1005, ORD-1003, ORD-1004. The order 60 days out lands in the middle.
Counting over all pairs and triples:
- Antisymmetry violations: 0 for all three comparators. Negating an overflowed difference gives the negated wrong answer, so the sign stays antisymmetric except at
Integer.MIN_VALUE, which these values never produce. - Transitivity violations: 12 triples for the truncating comparator, 15 for the subtracting one, 0 for the correct one.
That first row is worth noticing. A property test that only checks antisymmetry would pass these comparators. Transitivity is the property they break.
The subtracting comparator's worst case is direct: Integer.MAX_VALUE - (Integer.MIN_VALUE + 1) wraps to -2, so the largest adjustment sorts below the most negative.
What sorting does with a broken comparator
Arrays.sort and List.sort on objects use a merge-based algorithm that checks some invariants while it runs. The Java SE 25 documentation for Arrays.sort lists IllegalArgumentException, marked optional, if the comparator is found to violate the Comparator contract. Optional is the key word. The example sorts 2,000 random orders spread over 120 days with the truncating comparator, once per seed from 1 to 50:
- 14 runs threw
IllegalArgumentException: Comparison method violates its general contract! - 36 runs returned normally with the array out of order.
With seed 42 the array is out of order at index 3. With the correct comparator, every run sorts. So the exception is not a safety net. More often than not, in this measurement, the sort finished and handed back wrong data. The split depends on the data and on the JDK's sort implementation, so treat 14 out of 50 as one observation, not a rate to plan around.
What a TreeSet does with an inconsistent comparator
The TreeSet documentation is explicit: the ordering a set maintains must be consistent with equals if it is to correctly implement the Set interface, because a TreeSet performs all element comparisons with compare, and two elements that compare as zero are, from the standpoint of the set, equal.
A comparator that orders only by timestamp, even a correct one such as Comparator.comparingLong(Order::createdAtMillis), treats ORD-1003 and ORD-1004 as the same element, because they share a timestamp. Adding the five orders to a TreeSet built with it leaves 4 elements. One order is gone, and add simply returned false. A TreeMap keyed the same way would overwrite one order's value with the other's. Nothing is thrown.
The fix
Compare without arithmetic, and break ties on a unique key:
static final Comparator<Order> TOTAL_ORDER =
Comparator.comparingLong(Order::createdAtMillis)
.thenComparing(Order::id);comparingLong uses Long.compare, which compares values directly rather than subtracting them. For int fields, Integer.compare or Comparator.comparingInt do the same. The thenComparing(Order::id) step makes compare return zero only for the same order ID, so the ordering is a total order consistent with equals as long as equals is also based on the ID. With this comparator, the example's five orders sort by time, the TreeSet keeps all five, and there are no violations.
If you need nulls, use Comparator.nullsFirst or nullsLast around the key comparator rather than special-casing them inside a lambda. A hand-written null branch is one of the easiest ways to break antisymmetry, because it is natural to handle compare(null, x) and forget compare(x, null).
Finding the bad comparators you already have
- Search for comparator lambdas and
compareTomethods that subtract, and for casts of a long difference to int. Static analysis tools also have rules for this pattern. They are worth enabling, because the pattern is easy to recognise syntactically. - For every comparator used to key a sorted set or map, check that it ends in a unique key, or that you intend equal-comparing elements to be merged.
- Add a property test that draws a few hundred values, including the extremes of the field's type and values far apart, and counts violations of antisymmetry and transitivity. Exhaustive checking of triples is cheap for a few dozen values. The example counts all 125 triples of five orders.
- Check the input range against what the comparator assumes. A comparator that worked when timestamps were seconds in an int can break when someone changes the field to milliseconds.
Failure modes to test
- Two values more than 2^31 apart for long keys, and opposite-signed extremes for int keys.
- Equal keys with different identities, in every sorted collection the comparator is used for. Assert the size afterwards.
- A sort over a large random input, asserting that the output is ordered. Do not rely on the exception.
- Nulls in the key, if the type allows them.
- Comparators composed with
reversed(). Reversal preserves the contract if the original satisfies it, and preserves its bugs if it does not.
When this does not matter
If keys are small non-negative integers with a known bound, such as a priority from 0 to 9, subtraction cannot overflow and the comparator is correct. It is still worth replacing, because the bound is an assumption no compiler checks and the replacement costs nothing. If a collection never uses the comparator as identity, for example a list sorted for display, inconsistency with equals is harmless, but transitivity still matters for the sort itself.
Verification checklist
- No comparator in the codebase subtracts keys or casts a long difference.
- Every comparator that keys a sorted set or map ends with a unique key, or carries a comment saying merging is intended.
- A property test checks transitivity with extreme and widely spaced values.
- The example's numbers reproduce on your JDK: 12 and 15 transitivity violations, a 4-element time-only
TreeSet, and correct sorting with the total order.
Run the example yourself
The three comparators, the violation counts, the TreeSet and the 50-seed sort, with a plain-Java test of twelve checks. Companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.