Scrivio Interview library
DebuggingIntermediate8 min read · updated 12 November 2026

A batch job sorting 2 million records fails intermittently with java.lang.IllegalArgumentException: Comparison method violates its general contract! The comparator compares two double scores and returns 1 if a > b, -1 otherwise. What is wrong and how do you fix it?

The comparator never returns 0, so compare(a, a) is -1, and for two records with equal scores both compare(a, b) and compare(b, a) are -1, which breaks the rule that swapping the arguments must flip the sign. NaN scores make it worse, because every comparison with NaN is false. TimSort notices the inconsistency only in certain merge situations, which depend on the data, so the failure is intermittent. The fix is Comparator.comparingDouble(Rec::score) or Double.compare, which define a total order including NaN and -0.0, backed by a property-based test of the comparator contract.

Why this question is asked

This exception is one of the more confusing ones in Java, because the stack trace points into the JDK's sorting code, the same job succeeds on most nights, and the comparator looks obviously correct. Interviewers like it because the answer requires knowing the comparator contract precisely, understanding floating-point corner cases, and knowing enough about TimSort to explain why the failure depends on the data. In this answer, we will reproduce the bug, recap the contract, see exactly how this comparator breaks it, explain why the failure is intermittent, fix it, and write a test that would have caught it.

1Reproducing the Problem

Here is the comparator from the batch job, reduced to its essence.

Java
record Rec(long id, double score) {}
Comparator<Rec> broken = (x, y) -> x.score() > y.score() ? 1 : -1;
Rec a = new Rec(1, 0.5), b = new Rec(2, 0.5), n = new Rec(3, Double.NaN);
broken.compare(a, a); // -1: an element is 'less than' itself
broken.compare(a, b); // -1
broken.compare(b, a); // -1: both say 'I come first'
broken.compare(a, n); // -1: 0.5 > NaN is false
broken.compare(n, a); // -1: NaN > 0.5 is false too
recs.sort(broken); // on some inputs with many equal scores:
// java.lang.IllegalArgumentException: Comparison method violates its general contract!
// at java.base/java.util.TimSort.mergeHi(...)

Notice that the comparator is fine whenever the scores differ and are not NaN. It only misbehaves for ties and for NaN, which is why it passes casual testing and why the bug appears with real data, where 2 million records are very likely to include many equal scores.

2A Quick Recap of the Comparator Contract

The Comparator documentation asks for three properties. First, sign symmetry: sgn(compare(a, b)) must equal -sgn(compare(b, a)) for all a and b. Swapping the arguments must flip the answer, and if a equals b in this ordering, both directions must return 0. A direct consequence is that compare(a, a) must be 0. Second, transitivity: if a > b and b > c, then a > c. Third, consistency of equality: if compare(a, b) is 0, then a and c must compare the same way as b and c.

Sorting algorithms rely on these rules to avoid redundant comparisons. If they did not, a sort would have to compare every pair to be safe. TimSort in particular uses them to skip ahead quickly during merging, as we will see.

Broken comparator versus Double.compare
InputsbrokenDouble.compareContract needs
a = 0.5, a = 0.5 (same element)-100
a = 0.5, b = 0.5-1 both ways0 both waysopposite signs or both 0
0.5 and NaN-1 both ways-1 and 1 (NaN is largest)opposite signs
-0.0 and 0.0-1 both ways-1 and 1 (-0.0 first)opposite signs
0.4 and 0.5-1 and 1-1 and 1opposite signs

3How This Comparator Breaks It

With equal scores, the comparator says a < b and b < a at the same time. An ordering where each of two elements is smaller than the other has no consistent sorted result, so any algorithm that relies on the contract can reach a state that should be impossible.

NaN, the floating-point value for 'not a number', adds a second break. In IEEE 754 arithmetic, every ordered comparison involving NaN is false: NaN > x, NaN < x and even NaN == NaN are all false. So a NaN score compares as 'less than' everything, and everything compares as 'less than' it. A single NaN in the data, for example from a division of zero by zero in the scoring step, is enough to break transitivity across the whole list.

The two zeros are a smaller corner case. In floating point, 0.0 and -0.0 are distinct values that compare equal with the > and == operators, so they behave like any other tie in the broken comparator.

4Why the Failure Is Intermittent

Arrays and lists of objects are sorted with TimSort. For fewer than 32 elements, TimSort uses binary insertion sort, which never checks the contract; a bad comparator just produces some order. So small test inputs never fail. That answers the follow-up question about why the code worked in tests.

For larger inputs, TimSort finds sorted runs and merges them. During a merge it uses galloping: when one run keeps winning, it jumps ahead with a binary search instead of comparing element by element. That shortcut is only valid if the comparator is consistent. When TimSort reaches a state that a consistent comparator could never produce, typically one run running out when the bookkeeping says it cannot, it throws this IllegalArgumentException rather than returning a corrupted result.

Whether that state is reached depends on the exact order of the input, how many ties there are and where the NaNs fall. Most nights the data happens to avoid it; some nights it does not. The job did not change; the data did.

Step throughWhy some nights fail and others do not
  1. Fewer than 32 elements?
    YesBinary insertion sort, no check, some order returnedNoFind runs and merge them
  2. Do ties or NaNs meet during a galloping merge?
    YesBookkeeping becomes impossibleNoSort completes, order may still be wrong
  3. Impossible state detectedIllegalArgumentException: Comparison method violates its general contract!

3 steps in order. Play them, or step through them one at a time.

5The Fix: Use the Library's Comparison

Double.compare(x, y) defines a total order on all double values: -0.0 comes before 0.0, NaN is equal to itself and greater than every other value, including positive infinity, and all other values are ordered numerically. Comparator.comparingDouble uses it and avoids boxing the scores.

Java
Comparator<Rec> byScore = Comparator.comparingDouble(Rec::score);
// or: (x, y) -> Double.compare(x.score(), y.score())
byScore.compare(a, a); // 0
byScore.compare(a, b); // 0 and byScore.compare(b, a) is 0
byScore.compare(a, n); // -1 and byScore.compare(n, a) is 1: NaN sorts last
Comparator<Rec> stable = byScore.reversed().thenComparingLong(Rec::id); // highest first, ties by id
recs.sort(stable); // never throws for any data

Adding a tie-breaker such as the id makes the order fully deterministic, which is useful for a batch job whose output is compared between runs. It is also worth asking why NaN scores exist at all. Sorting them last stops the crash, but a NaN usually means the scoring step had a bug, so the job should count and log them, or reject them at the point where scores are computed.

6A Property-Based Test for the Comparator

A property-based test checks a rule on many randomly generated inputs instead of a few hand-picked ones. The contract is a perfect candidate, and the random inputs should deliberately include ties, NaN, -0.0 and infinities, because those are where comparators break.

Java
@Test
void comparatorObeysContract() {
// cmp is the comparator under test; rec() builds a Rec with a special value or a random double
double[] specials = {0.0, -0.0, Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.5};
Random rnd = new Random(42);
for (int i = 0; i < 100_000; i++) {
Rec a = rec(rnd, specials), b = rec(rnd, specials), c = rec(rnd, specials);
assertEquals(Integer.signum(cmp.compare(a, b)), -Integer.signum(cmp.compare(b, a))); // symmetry
if (cmp.compare(a, b) > 0 && cmp.compare(b, c) > 0) assertTrue(cmp.compare(a, c) > 0); // transitivity
assertEquals(0, cmp.compare(a, a)); // reflexive zero
}
}
// With the broken comparator: fails at once on the symmetry check (-1 vs 1)
// With comparingDouble: passes

Libraries such as jqwik make this style easier, with generators and automatic shrinking of failing cases to the smallest example. Even the plain loop above would have caught the bug in milliseconds, on the first pair of equal scores.

7Follow-up questions

Why did the code work on small test inputs?

Because TimSort sorts arrays and lists of fewer than 32 elements with binary insertion sort, which never checks the contract, and because small hand-written test data rarely contains equal scores or NaN. The broken comparator just produced some order without complaint. The contract check only happens during merging of runs, which needs larger inputs with the right pattern of ties.

Can we switch the old merge sort back on to make the error go away?

The JDK has had a system property, java.util.Arrays.useLegacyMergeSort, that selects the pre-Java 7 merge sort; check whether your version still honours it. It hides the symptom but not the bug: the old sort does not throw, yet with an inconsistent comparator the output order is still meaningless. Fixing the comparator is the only real solution.

Are there other common ways to break the contract?

Yes: subtraction comparators that overflow, comparators that read mutable fields that change during the sort, comparators that use a random tie-breaker, and comparators that are inconsistent across keys, such as comparing by one field for some objects and another field for others. All of them can trigger the same exception.

8Conclusion

In this answer, we saw that a comparator returning 1 if a > b and -1 otherwise never returns 0, so ties and NaN scores break sign symmetry and transitivity. TimSort detects the inconsistency only when a merge reaches an impossible state, which depends on the data, so the job fails intermittently and never on inputs under 32 elements. Comparator.comparingDouble or Double.compare give a total order including NaN and -0.0, a tie-breaker makes the order deterministic, and a property-based test of the contract catches such bugs immediately.

What to say in the interviewAbout 100 seconds aloud

Open with

The comparator never returns zero. For two records with equal scores, compare(a, b) is minus one and compare(b, a) is also minus one, so each says it comes first, and even compare(a, a) is minus one.

Then, if they want more

That breaks the contract that swapping the arguments flips the sign. NaN makes it worse, because every comparison with NaN is false, so a NaN score is less than everything and everything is less than it, which breaks transitivity. The reason it fails only sometimes is TimSort.

Below 32 elements it uses binary insertion sort, which never checks anything, so small tests pass. For larger inputs it merges runs and uses galloping, which relies on the comparator being consistent.

When ties or NaNs put the merge into a state that a valid comparator could never produce, TimSort throws Comparison method violates its general contract instead of returning garbage. Whether that state is reached depends on the exact data, so with two million records it fails on some nights and not others.

The fix is to use Comparator.comparingDouble(Rec::score), or Double.compare, which defines a total order: minus zero before zero, and NaN equal to itself and after everything else. I'd add a tie-breaker like the id for a deterministic order, and investigate where NaN scores come from.

Finally I'd add a property-based test that checks sign symmetry and transitivity on random data including ties, NaN and minus zero, which would have caught this immediately.

About this answer

Last updated
12 November 2026
Versions it names
Java 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A batch job sorting 2 million records fails intermittently with...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/d48bc9b946/