Video in progress

Why is it dangerous to synchronize on, or use == with, value-based classes like Integer or LocalDate, and how does Valhalla relate to this?

The identity of value-based classes isn't guaranteed: the same value may or may not be one object, so tying a lock or == to them gives random behavior. In future Valhalla value classes there will be no identity at all, and that kind of code will stop working.

📖 Answer

java.lang.Integer, Long, Optional, LocalDate, Duration, the results of List.of(...) and others are marked "value-based" in the docs. That's a promise: compare them only with equals, and don't rely on identity.

Why a lock is dangerous:

private final Integer lock = 0;     // Integer.valueOf(0): cached, a shared object!
synchronized (lock) { ... }

Because of the Integer cache inside the JVM, this lock can be the same object as another library's Integer 0, so two unrelated pieces of code block each other. synchronized on String literals has the same problem (the interned pool).

Since Java 16 (JEP 390):

  • the constructors of value-based classes are @Deprecated(forRemoval = true): use Integer.valueOf(5), not new Integer(5);
  • javac warns when you use synchronized on them;
  • -XX:DiagnoseSyncOnValueBasedClasses=1 makes it an error at runtime, and =2 writes a log.

Comparing with ==: Integer is cached in the range -128..127 and not outside it, which is well known. But for LocalDate and Optional, == sometimes "works" too, because the implementation caches some values. A future JDK could change the cache.

The link to Valhalla (JEP 401, value classes, not final yet): the plan is for these classes to become real value classes in the future. They have no identity, == compares by fields, and synchronized fails with a runtime error. The JVM can store them "flat" inside an array instead of as heap objects, which is a big win for memory and cache locality.

What to do now:

  • for a lock, use only a dedicated object: private final Object lock = new Object(); or a ReentrantLock;
  • don't rely on IdentityHashMap, System.identityHashCode or WeakReference for value-based types;
  • write your own value classes (Money, UserId) as a record or final right now, and not dependent on identity, so converting them to value classes later is a one-word change;
  • turn these rules on in static analysis (Error Prone has the relevant checks).