Video in progress

After a JDK upgrade, the order of elements changed in tests and reports. What is the cause, and how do you protect against it in the future?

The code relies on the iteration order of HashMap/HashSet or Set.of/Map.of. That order is not guaranteed, and it changes between JDK versions, and in the case of Set.of even on every JVM start. The protection: where you need order, express it with the type, and catch order dependence in tests on purpose.

📖 Answer

This has happened several times in history:

  • in Java 8 the internal structure of HashMap and the hash mixing changed, so an order that looked "stable" in Java 7 became different;
  • in Java 9, the iteration order of Set.of/Map.of is shuffled with a random SALT at startup. The same code gives a different order on every run. That is deliberate, so that people don't rely on order.

How it shows up on prod: the order of fields in a JSON response changed and a snapshot test on the client side failed; the columns of a CSV report got swapped; a business decision made on the "first found" element gave a different result; a cache key or signature computed from a hash stopped matching.

The fix:

// when you need insertion order
Map<String, Object> fields = new LinkedHashMap<>();
// when you need order by key
Map<String, Object> sorted = new TreeMap<>(source);

Jackson has ORDER_MAP_ENTRIES_BY_KEYS and @JsonPropertyOrder. A SQL result without an ORDER BY has the same problem.

Protection for the future, at the organization level:

  1. A code review rule: any sequence that leaves the system (API, file, signature, hash) is built with an explicitly ordered type or an explicit sort.
  2. Comparisons that don't depend on order in tests: AssertJ containsExactlyInAnyOrder, and containsExactly where order matters, so the intent is visible.
  3. A separate pipeline in CI that runs ahead of time on the new JDK (for example, a nightly with the next LTS). Order-dependent tests fail there first.
  4. Running tests in random order (JUnit MethodOrderer.Random) finds hidden dependencies earlier.