🔹 Introduction
Deadlock is one of the most critical concepts in Java multithreading and is frequently asked in interviews.
👉 Interviewers often ask:
“What is deadlock? Can you create one in Java?”
In this article, we will:
- Understand deadlock
- Create a deadlock
- Learn how to prevent it
🔹 What is Deadlock?
A deadlock occurs when two or more threads are waiting for each other indefinitely, and none of them can proceed.
👉 Simple idea:
- Thread 1 holds Resource A and waits for B
- Thread 2 holds Resource B and waits for A
💥 Both get stuck forever
🖼️ Visualization (Understand Easily)
Thread 1 → holds Lock A → waiting for Lock B
Thread 2 → holds Lock B → waiting for Lock A
Result: DEADLOCK
🔹 Java Code to Create Deadlock
public class DeadlockExample {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
synchronized (lock1) {
System.out.println("Thread 1 acquired lock1");
try { Thread.sleep(100); } catch (Exception e) {}
synchronized (lock2) {
System.out.println("Thread 1 acquired lock2");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (lock2) {
System.out.println("Thread 2 acquired lock2");
try { Thread.sleep(100); } catch (Exception e) {}
synchronized (lock1) {
System.out.println("Thread 2 acquired lock1");
}
}
});
t1.start();
t2.start();
}
}
🔍 Why Deadlock Happens
Deadlock occurs due to 4 conditions:
- Mutual Exclusion
- Hold and Wait
- No Preemption
- Circular Wait
👉 All must be true
🔹 How to Prevent Deadlock
✅ 1. Lock Ordering
Always acquire locks in same order
✅ 2. Use Try Lock
Use timeout-based locking
✅ 3. Avoid Nested Locks
Reduce dependency between resources
✅ 4. Use Higher-Level APIs
Use:
-
ExecutorService - Concurrency utilities
🔹 Time Complexity
- Not applicable (thread blocking issue)
🔹 Key Takeaways
✔ Deadlock = threads waiting forever
✔ Happens due to circular dependency
✔ Can be prevented using lock strategies
✔ Very important interview question
🔹 Conclusion
Deadlock is a critical concept in multithreading. Understanding how it occurs and how to prevent it is essential for backend developers.
Comments
Post a Comment