DEV Community

Narednra Reddy Yadama
Narednra Reddy Yadama

Posted on

๐Ÿงจ What is Deadlock?

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)