What is Deadlock and How to Avoid It in Java

πŸ’‘ Concept: Deadlock

A deadlock in Java occurs when two or more threads wait for each other’s locks indefinitely, creating a circular dependency that halts execution.

πŸ“˜ Quick Intro

Deadlocks can happen when multiple threads lock shared resources in inconsistent orders. Avoiding deadlocks is essential in multithreaded applications.

🧠 Analogy

Think of two people trying to pass through a narrow hallway, but both insist the other go first. Neither moves, and both are stuck forever. That’s a deadlock.

πŸ”§ Technical Explanation

  • Deadlock involves four conditions: mutual exclusion, hold and wait, no preemption, and circular wait.
  • Occurs when two threads hold a lock and try to acquire the other’s lock simultaneously.
  • Java threads use object monitors via synchronized, which can cause deadlock if not managed carefully.

🎯 How to Avoid Deadlocks

  • βœ… Always acquire locks in a consistent global order.
  • βœ… Use timeout-based lock attempts with tryLock() from ReentrantLock.
  • βœ… Minimize the number of synchronized blocks.
  • βœ… Avoid nested locks if possible.

πŸ’» Example: Deadlock Scenario


public class DeadlockExample {
    static final Object Lock1 = new Object();
    static final Object Lock2 = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (Lock1) {
                System.out.println("Thread 1: Holding Lock1...");
                try { Thread.sleep(100); } catch (InterruptedException e) {}
                synchronized (Lock2) {
                    System.out.println("Thread 1: Acquired Lock2!");
                }
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized (Lock2) {
                System.out.println("Thread 2: Holding Lock2...");
                try { Thread.sleep(100); } catch (InterruptedException e) {}
                synchronized (Lock1) {
                    System.out.println("Thread 2: Acquired Lock1!");
                }
            }
        });

        t1.start();
        t2.start();
    }
}

❓ Interview Q&A

Q1: What causes a deadlock?
A: Circular waiting between threads for resources.

Q2: Can synchronized blocks cause deadlocks?
A: Yes, if not handled carefully.

Q3: How can deadlock be prevented?
A: By acquiring locks in a consistent order.

Q4: What is tryLock used for?
A: To attempt a lock with a timeout, helping avoid deadlock.

Q5: Can deadlocks be detected at runtime?
A: Yes, using tools like jConsole or thread dumps.

Q6: What is circular wait?
A: A condition where each thread waits for a resource held by another.

Q7: Can volatile prevent deadlock?
A: No, volatile deals with visibility, not synchronization.

Q8: Do atomic variables prevent deadlock?
A: No, they prevent race conditions, not deadlocks.

Q9: What’s the best way to debug deadlock?
A: Analyze thread dumps and lock ownership graphs.

Q10: What’s the difference between livelock and deadlock?
A: In livelock, threads keep changing states but make no progress; in deadlock, they are stuck forever.

πŸ“ MCQs

Q1. Which condition is required for deadlock?

  • Lock fairness
  • High CPU
  • Circular wait
  • Garbage collection

Q2. How can you prevent deadlocks?

  • Use synchronized everywhere
  • Lock resources in a consistent order
  • Ignore thread safety
  • Use volatile variables

Q3. What tool can detect deadlocks?

  • javac
  • JAR signer
  • jConsole
  • JRE Cleaner

Q4. Does volatile prevent deadlock?

  • Yes
  • No
  • Sometimes
  • Only on Linux

Q5. Which method provides timeout locking?

  • lock()
  • sync()
  • tryLock()
  • grab()

Q6. What is deadlock?

  • Memory leak
  • Slow I/O
  • Threads waiting on each other’s locks
  • Queue starvation

Q7. What causes circular wait?

  • No resource
  • Each thread waiting for a resource held by another
  • Static method call
  • Priority boost

Q8. Is deadlock a compile-time error?

  • Yes
  • No
  • Depends
  • Only in debug mode

Q9. Can nested synchronized blocks cause deadlock?

  • No
  • Yes
  • Not possible
  • Only if synchronized is static

Q10. Does thread sleep affect deadlock?

  • Yes
  • No, but may increase likelihood
  • Always prevents it
  • Always causes it

πŸ’‘ Bonus Insight

Deadlocks are easier to prevent than to fix. Always design concurrency with locking order and minimal shared resources in mind.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ” Navigation

Share:

Tags:


Feedback Modal Popup