A deadlock in Java occurs when two or more threads are blocked forever, each waiting for a resource held by another thread. Deadlocks are common in multithreaded and concurrent Java applications.
Deadlock happens due to four necessary conditions:
// Demonstration of deadlock using two threads and two resources
class DeadlockExample {
static final Object resource1 = new Object();
static final Object resource2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
synchronized (resource1) {
// Thread 1 locks resource1
try { Thread.sleep(100); } catch (Exception e) {}
synchronized (resource2) {
// Thread 1 tries to lock resource2
}
}
});
Thread t2 = new Thread(() -> {
synchronized (resource2) {
// Thread 2 locks resource2
try { Thread.sleep(100); } catch (Exception e) {}
synchronized (resource1) {
// Thread 2 tries to lock resource1
}
}
});
t1.start();
t2.start();
}
}
Thread T1 holds resource1 and waits for resource2, while Thread T2 holds resource2 and waits for resource1. Both threads wait forever — causing a deadlock.
ReentrantLock with timeout