Video in progress
This code was supposed to run operations for one account one after another, but the balance still gets corrupted. What's wrong?
@Service
public class LedgerService {
public void apply(long accountId, long delta) {
synchronized (Long.valueOf(accountId)) { // "a lock for this account"
long balance = repo.balance(accountId);
repo.saveBalance(accountId, balance + delta);
}
}
}
synchronized (Long.valueOf(accountId)) takes a lock on a boxed Long. Outside the range -128..127, every autoboxing creates a new object, so threads take different monitors and there's no protection. With small IDs it's the opposite: you share one cached object with unrelated code.
📖 Answer
Long.valueOf caches only the range -128..127. If the ID is 1,000,042, two threads get two different Long objects and each enters its own monitor. In tests the IDs were small, so everything worked.
With small IDs there's a different problem: Long.valueOf(7) is a single object for the whole JVM. If other code also locks on that object, you get unexpected contention or a deadlock. Locking on a String, especially an intern()ed one, is just as dangerous.
Since JDK 16, classes like Long and Integer are marked "value-based": if you use synchronized on them, javac warns (-Xlint:synchronization), and at runtime you can turn on diagnostics with -XX:DiagnoseSyncOnValueBasedClasses. In the future, with Valhalla, such objects may not have a monitor at all.
If you need a per-key lock:
// striped lock: bounded memory, some keys share a lock
private final ReentrantLock[] stripes = IntStream.range(0, 256)
.mapToObj(i -> new ReentrantLock()).toArray(ReentrantLock[]::new);
ReentrantLock lockFor(long id) {
return stripes[(int) Math.floorMod(id, (long) stripes.length)];
}
Other options: a short, in-memory change inside ConcurrentHashMap.compute(id, ...), or Guava's Striped.lazyWeakLock(n).
But the main question in this code is a different one: the balance is in the DB. Any lock inside the JVM only works for one instance, and a second pod doesn't see it. The right fix is at the DB level: UPDATE accounts SET balance = balance + :delta WHERE id = :id, SELECT ... FOR UPDATE, or @Version. A JVM lock here can only be an optimization that reduces contention hitting the DB, not a correctness guarantee.
Sign up to mark studied questions and save your progress.