What is a deadlock in Java

A deadlock in Java occurs when two or more threads are blocked forever, each waiting for the other to release a resource. This situation arises when two or more threads hold resources that the others need to continue executing. In a deadlock scenario, the threads cannot proceed because they are each waiting for another to release a lock.

To illustrate, consider the following example:

public class DeadlockExample { private final Object lock1 = new Object(); private final Object lock2 = new Object(); public void method1() { synchronized (lock1) { System.out.println("Thread 1: Holding lock 1..."); try { Thread.sleep(100); } catch (InterruptedException e) {} System.out.println("Thread 1: Waiting for lock 2..."); synchronized (lock2) { System.out.println("Thread 1: Acquired lock 2!"); } } } public void method2() { synchronized (lock2) { System.out.println("Thread 2: Holding lock 2..."); try { Thread.sleep(100); } catch (InterruptedException e) {} System.out.println("Thread 2: Waiting for lock 1..."); synchronized (lock1) { System.out.println("Thread 2: Acquired lock 1!"); } } } public static void main(String[] args) { DeadlockExample de = new DeadlockExample(); Thread t1 = new Thread(de::method1); Thread t2 = new Thread(de::method2); t1.start(); t2.start(); } }

Deadlock Java concurrency multithreading issues thread synchronization resource contention