A deadlock occurs when two or more threads are waiting for each otherโs locks, and none can proceed. Itโs like two people holding one key each, refusing to give theirs up until they get the otherโs. Result? Permanent standstill.
๐ The 4 Deadlock Conditions (Coffman Conditions)
โซ๏ธ Deadlock can only happen if all four of these are true:
โซ๏ธ Mutual Exclusion โ Only one thread can hold a lock at a time
โซ๏ธ Hold and Wait โ A thread holds one lock and waits for another
โซ๏ธ No Preemption โ Locks canโt be forcibly taken away
โซ๏ธ Circular Wait โ A cycle of threads waiting on each other
๐งช Code Example: Deadlock in Action
class DeadlockDemo {
final Object lockA = new Object();
final Object lockB = new Object();
void methodA() {
synchronized (lockA) {
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (lockB) {
System.out.println("Thread A acquired both locks");
}
}
}
void methodB() {
synchronized (lockB) {
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (lockA) {
System.out.println("Thread B acquired both locks");
}
}
}
public static void main(String[] args) {
DeadlockDemo demo = new DeadlockDemo();
new Thread(demo::methodA).start();
new Thread(demo::methodB).start();
}
}
๐ง What Happens Here?
๐น Thread A locks lockA, then tries to get lockB
๐นThread B locks lockB, then tries to get lockA
๐นBoth threads are stuckโeach waiting for the other to release a lock ๐ฅ Deadlock!
๐ก๏ธ How to Prevent Deadlock
โ
Lock Ordering: Always acquire locks in a consistent global order
โ
Try-Lock with Timeout: Use ReentrantLock.tryLock() to avoid indefinite waiting
โ
Avoid Nested Locks: Minimize locking inside other locks
โ
Use Concurrency Utilities: Prefer ExecutorService, ConcurrentHashMap, etc.
๐ Final Thought
Deadlocks donโt crash your appโthey freeze it. Theyโre sneaky, hard to debug, and often missed in testing. Design defensively, and always think in terms of lock strategy.
Top comments (0)