Java Concurrency Program · CD13
Create and Fix a Deadlock in Java
Thread 1 holds lock A and wants B. Thread 2 holds B and wants A. Neither can move, forever. That is a deadlock.
Problem Statement
Write transfer(from, to, amount) that locks both accounts while it moves money. Two threads transfer 1 rupee 10,000 times each, one from A to B and the other from B to A.
Both threads must always finish, and the total balance must stay at 2000.
Input/Output Examples
lock from, then lock toOutputmay hang foreverExplanation: the threads lock the same pair in opposite orders.always lock the smaller id firstOutputboth threads finishExplanation: a circular wait is impossible.after 10,000 transfers each wayOutputA=1000, B=1000, total=2000Explanation: the transfers cancel out and no money is lost.Visual Explanation
- Thread 1holdsAwantsBtransfer(A, B)
- Thread 2holdsBwantsAtransfer(B, A) circular wait
- Fixboth lockAthen Border by account id no cycle
- Doneboth finish
A deadlock needs four conditions at once: mutual exclusion, hold and wait, no pre-emption and a circular wait. Each fix removes one of them.
Approaches
Both approaches make the transfers deadlock-free. The first removes the circular wait; the second removes hold and wait.
Approach 1: Global Lock Order (Recommended)
Idea: decide which account to lock first by comparing ids, so every thread takes the two locks in the same order.
- Pick
firstas the account with the smaller id andsecondas the other. - Lock
first, thensecond, with nestedsynchronizedblocks. - Move the money inside both locks.
Time: O(1) · Space: O(1). per transfer, excluding the time spent waiting for the locks.
Approach 2: tryLock() With Back-Off
Idea: try to take both ReentrantLocks with a short timeout; if the second is busy, release the first, pause briefly and try again.
- Call
from.lock.tryLock(1, MILLISECONDS). - If it succeeds, try
to.lockthe same way. - If either fails, unlock what you hold and back off for a random moment.
- Repeat until both locks are held, then transfer.
Time: O(1) expected · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both tabs print the same output; the program exits explicitly so a regression to a deadlock cannot hang it.
Approach 1: Global Lock Order (Recommended)
Simple, fast and the standard fix when every lock has a natural order.
public class DeadlockLockOrder {
static class Account {
final int id;
int balance;
Account(int id, int balance) { this.id = id; this.balance = balance; }
}
// Deadlock needs two threads taking the same two locks in opposite orders.
// Always locking the account with the smaller id first removes that possibility.
static void transfer(Account from, Account to, int amount) {
Account first = from.id < to.id ? from : to;
Account second = from.id < to.id ? to : from;
synchronized (first) {
synchronized (second) {
from.balance -= amount;
to.balance += amount;
}
}
}
public static void main(String[] args) throws InterruptedException {
Account a = new Account(1, 1000);
Account b = new Account(2, 1000);
// Two threads transfer in opposite directions at the same time, 10,000 times each
Thread t1 = new Thread(() -> { for (int i = 0; i < 10_000; i++) transfer(a, b, 1); });
Thread t2 = new Thread(() -> { for (int i = 0; i < 10_000; i++) transfer(b, a, 1); });
t1.start();
t2.start();
t1.join(5000);
t2.join(5000);
boolean finished = !t1.isAlive() && !t2.isAlive();
System.out.println("both transfer threads finished (no deadlock): " + finished);
System.out.println("balances: A=" + a.balance + ", B=" + b.balance + ", total=" + (a.balance + b.balance));
System.exit(0);
}
}
both transfer threads finished (no deadlock): true balances: A=1000, B=1000, total=2000
Time complexity: O(1) · Space complexity: O(1).
Approach 2: tryLock() With Back-Off
Works even without a natural lock order, at the cost of retries; the random back-off prevents livelock.
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class DeadlockTryLock {
static class Account {
final int id;
int balance;
final ReentrantLock lock = new ReentrantLock();
Account(int id, int balance) { this.id = id; this.balance = balance; }
}
// Take both locks with tryLock(); if the second is busy, release the first and retry after a short pause
static void transfer(Account from, Account to, int amount) {
while (true) {
try {
if (from.lock.tryLock(1, TimeUnit.MILLISECONDS)) {
try {
if (to.lock.tryLock(1, TimeUnit.MILLISECONDS)) {
try {
from.balance -= amount;
to.balance += amount;
return;
} finally {
to.lock.unlock();
}
}
} finally {
from.lock.unlock();
}
}
Thread.sleep(0, ThreadLocalRandom.current().nextInt(1000)); // back off a little
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
public static void main(String[] args) throws InterruptedException {
Account a = new Account(1, 1000);
Account b = new Account(2, 1000);
// Two threads transfer in opposite directions at the same time, 10,000 times each
Thread t1 = new Thread(() -> { for (int i = 0; i < 10_000; i++) transfer(a, b, 1); });
Thread t2 = new Thread(() -> { for (int i = 0; i < 10_000; i++) transfer(b, a, 1); });
t1.start();
t2.start();
t1.join(5000);
t2.join(5000);
boolean finished = !t1.isAlive() && !t2.isAlive();
System.out.println("both transfer threads finished (no deadlock): " + finished);
System.out.println("balances: A=" + a.balance + ", B=" + b.balance + ", total=" + (a.balance + b.balance));
System.exit(0);
}
}
both transfer threads finished (no deadlock): true balances: A=1000, B=1000, total=2000
Time complexity: O(1) expected · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Global Lock Order | O(1) | O(1) |
| tryLock() With Back-Off | O(1) expected | O(1) |
Each transfer does a constant amount of work. Ordered locking never retries; tryLock() may retry a few times under contention.
Interview Tips and Recommended Approach
- Name the four Coffman conditions and say which one your fix breaks.
- Find deadlocks with a thread dump.
jstackreports "Found one Java-level deadlock". - Avoid calling unknown code while holding a lock; it may take other locks in any order.
- Prefer fewer, coarser locks when the contention is low; one lock cannot deadlock with itself.
Recommended Approach: Global Lock Order
Why: it removes the cause of the deadlock instead of recovering from it, adds no retries and is easy to explain.