Tracing the actual lock-acquisition order in this exact snippet shows it does not deadlock as written, which is worth establishing precisely before proposing fixes: transferTo always acquires lockA (its own) first, then lockB (the other account's) second. receiveFrom always acquires lockA (the other account's) first, then lockB (its own) second. Every code path acquires an "A-role" lock before a "B-role" lock, and never the reverse, for any combination of this/other. That is a consistent two-level lock hierarchy (all A-locks before all B-locks), and a consistent hierarchy like that is deadlock-free by construction: a circular wait needs some thread to hold a lock another thread needs while itself waiting on a lock the first thread holds, and no two concurrent calls here ever end up wanting the same pair of locks in reversed order. This was confirmed by simulating the exact lock-acquisition structure (each account with two independent lock objects, in Python with threading.Lock standing in for synchronized, since Java itself wasn't available in this environment) and running every pairwise combination of transferTo/receiveFrom concurrently, plus a 2000-iteration stress run in both directions with zero delay: all completed without blocking.
java
public class Account {
private final Object lockA = new Object();
private final Object lockB = new Object();
public void transferTo(Account other, int amount) {
synchronized (lockA) { synchronized (other.lockB) { /* transfer */ } }
}
public void receiveFrom(Account other, int amount) {
synchronized (other.lockA) { synchronized (lockB) { /* apply */ } }
}
}
The real bug pattern this code is easy to confuse with
The classic version of this deadlock happens when there is a single lock per account, acquired in reversed order across two call directions, for example:
java
public class Account {
private final Object lock = new Object();
public void transferTo(Account other, int amount) {
synchronized (lock) {
synchronized (other.lock) { /* transfer */ }
}
}
}
If X.transferTo(Y) and Y.transferTo(X) run concurrently here, thread 1 holds X.lock waiting for Y.lock, while thread 2 holds Y.lock waiting for X.lock: a genuine circular wait, and neither thread can proceed. This is the scenario the two-lock version above superficially resembles but, because it splits the single lock into a distinct "A" and "B" per account and always acquires A before B on every path, it does not actually reproduce it. Any change that collapses lockA/lockB back into one lock, or that adds a future method acquiring lockB before lockA, would reintroduce exactly this hazard, so the design is fragile even though this specific snippet is safe today.
Fixes and mitigations (apply to the single-lock pattern, or as defense-in-depth here)
- Total lock ordering independent of call direction: always acquire locks in a fixed global order (e.g., by a stable account ID, lower ID first) regardless of which account is "self" versus "other." This is the standard, architecturally simplest fix, and it's deadlock-free by construction the same way the two-role split above happens to be, but without depending on every future method preserving an A-before-B convention by convention alone.
tryLock with a timeout instead of blocking synchronized, retrying (with backoff/jitter) on failure to acquire, so a would-be deadlock becomes a bounded retry instead of a permanent stall.
- A single coarser lock (one lock per pair of accounts, or a global transfer lock), trading concurrency for simplicity when transfer volume doesn't need fine-grained per-account locking.
Detecting it in production
JVM thread dumps (jstack) explicitly report a "Found one Java-level deadlock" section naming the exact threads and locks involved when a genuine circular wait exists; a monitoring alert on threads stuck in BLOCKED state for longer than a threshold is a cheap early warning before a full stall is noticed by users. For code shaped like this two-lock version, absence of that jstack section (paired with the ordering analysis above) is itself useful confirmation that a reported "hang" has a different cause, such as an unrelated slow call held inside one of the synchronized blocks rather than a lock-ordering deadlock.
Trade-offs and pitfalls
Fix 1 (total ordering) is preferred because it's deadlock-free by construction and doesn't add retry latency; fix 2 (tryLock+timeout) is a reasonable fallback when a stable total order is hard to establish across the whole codebase, but it adds complexity and needs careful backoff to avoid livelock (both sides retrying in lockstep and failing forever). The broader pitfall this snippet illustrates: a locking scheme that happens to avoid deadlock today because of an incidental structural property (two distinct lock roles always acquired in the same order) is not the same thing as a scheme that is deadlock-free by design, and should not be trusted to stay safe as the code evolves.