Video in progress

In a library or shared module, what is the difference between source compatibility and binary compatibility? Which changes silently break them?

Source compatibility means user code recompiles against the new version. Binary compatibility means a jar compiled against the old version keeps working without recompiling. Some changes keep one and break the other, and the error only shows up at runtime as NoSuchMethodError.

📖 Answer

This happens a lot in multi-service projects: common-lib was updated from 2.3 to 2.4, one service wasn't rebuilt, but the classpath has the new jar, and on prod you get NoSuchMethodError.

Source compatible, not binary compatible:

// v1
public void notify(int userId) { ... }
// v2
public void notify(long userId) { ... }

notify(5) works on recompilation (int → long widening). But the old bytecode looks for the descriptor notify(I)V, and it isn't found.

Other changes like this:

  • changing the return type, even to a subtype (Object → String): the descriptor changes;
  • widening a parameter type to a supertype (ArrayList → List);
  • turning a method from an instance method into a static one: obj.m() still compiles, but the invokevirtual in old bytecode now gives IncompatibleClassChangeError;
  • changing the value of a public static final constant: it was inlined into the caller's code, so the old value stays (a silent "wrong value").

Binary compatible, not source compatible:

  • adding a new checked exception: old bytecode works, but on recompilation a catch is required;
  • adding a new overload to an existing method: old bytecode works, but on recompilation a call like send(null) can become "ambiguous".

Breaks both: deleting a public method, making a class final, adding an abstract method.

Protection:

  • put japicmp or Revapi in CI and check against the previous release;
  • semver: a binary break only in a major version;
  • keep the old method, add the new one and mark the old one @Deprecated(forRemoval = true);
  • if a value may change, expose constants through a method, not a static final field.