Video in progress
What happens if you use `==` or `synchronized` on value-based classes like `Integer`, `LocalDate` or `Optional`?
Relying on identity of value-based classes is wrong: == sometimes gives true and sometimes false (depending on a cache), and synchronized on them can end up sharing the same lock with other code. Since Java 16 the compiler warns about synchronizing on them.
📖 Answer
The classic example:
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b); // true: Integer cache (-128..127)
System.out.println(c == d); // false: each is a new object
In tests with small IDs everything works, and on prod the comparison "breaks" once IDs go above 128. Always use equals, or convert to a primitive.
With a lock:
private final Integer lock = 0; // a shared cached object!
synchronized (lock) { ... }
If another library also synchronizes on Integer.valueOf(0), you get unexpected contention or a deadlock. With JEP 390 (Java 16), javac warns about this, and -XX:DiagnoseSyncOnValueBasedClasses reports it at runtime. The new Integer(...) constructors are deprecated for removal.
The list of value-based classes is marked in the javadoc: the wrapper types (Integer, Long...), Optional, the java.time types, results of List.of(). The rule for them is to assume they have no identity: don't use ==, don't lock on them, don't use them as IdentityHashMap keys. This is preparation for value classes from Project Valhalla.
For a lock, always use a dedicated private final Object lock = new Object(); or a ReentrantLock.
Sign up to mark studied questions and save your progress.