Java.Multithreading.Deadlock

A deadlock is a situation in multithreaded programming where two or more threads are blocked forever, each waiting for the other to release a lock.

It’s like two people trying to pass each other in a narrow hallway:

  • Person A won’t move until Person B moves,
  • and Person B won’t move until Person A moves.
    → So neither moves – and that’s deadlock.

🧱 Deadlock Conditions (Coffman Conditions)

For a deadlock to occur, all four of these must be true:

  1. Mutual Exclusion – Only one thread can hold a lock at a time.
  2. Hold and Wait – A thread holding a lock is waiting to acquire another lock held by another thread.
  3. No Preemption – Locks can’t be forcibly taken; they must be released voluntarily.
  4. Circular Wait – There’s a cycle of threads, each waiting on a lock held by the next in the cycle.
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 ignored) {}
                System.out.println("Thread 1: Waiting for Lock2...");
                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 ignored) {}
                System.out.println("Thread 2: Waiting for Lock1...");
                synchronized (Lock1) {
                    System.out.println("Thread 2: Acquired Lock1.");
                }
            }
        });

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

🧠 What Happens Here?

  • t1 locks Lock1 and waits for Lock2.
  • t2 locks Lock2 and waits for Lock1.
  • Both threads wait forever → 💥 deadlock.

🛡️ How to Avoid Deadlocks

  • Lock ordering: Always acquire locks in a consistent global order.
  • Try-and-timeout: Use tryLock() with timeout (from ReentrantLock) to back out if deadlock might occur.
  • Avoid nested locks: Minimize holding multiple locks at once.
  • Deadlock detection: Use tools or thread dumps to analyze blocked threads.
This entry was posted in Без рубрики. Bookmark the permalink.