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)