Category: java
What Is Deadlock?
Published on 27 Oct 2026
Explanation
Deadlock happens when threads wait indefinitely for locks held by each other. For example, one thread holds lock A and waits for B, while another holds B and waits for A.
Code:
public class DeadlockDemo {
static final Object A = new Object(), B = new Object();
public static void main(String[] args) {
new Thread(() -> { synchronized (A) { synchronized (B) { } } }).start();
new Thread(() -> { synchronized (B) { synchronized (A) { } } }).start();
}
}
Explanation
Deadlock requires mutual exclusion, hold and wait, no preemption, and circular wait. Prevention techniques aim to break at least one of these conditions, such as by imposing a consistent order for acquiring locks.
Code:
public class LockOrderDemo {
static final Object FIRST = new Object(), SECOND = new Object();
static void task() {
synchronized (FIRST) {
synchronized (SECOND) {
System.out.println("Acquired locks in a consistent order");
}
}
}
public static void main(String[] args) {
new Thread(LockOrderDemo::task).start();
new Thread(LockOrderDemo::task).start();
}
}
Explanation
Always acquiring multiple locks in the same global order prevents circular wait for those locks. Every code path that acquires the same pair of locks must follow the same ordering rule.
Code:
class TransferLocks {
private final Object accountA = new Object();
private final Object accountB = new Object();
public void transfer() {
synchronized (accountA) {
synchronized (accountB) {
System.out.println("Transfer protected");
}
}
}
}
Explanation
ReentrantLock.tryLock() attempts to acquire a lock without blocking indefinitely. When acquiring multiple locks, release any acquired lock if another cannot be obtained, and always unlock in a finally block.
Code:
import java.util.concurrent.locks.ReentrantLock;
public class TryLockDemo {
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
if (lock.tryLock()) {
try { System.out.println("Lock acquired"); }
finally { lock.unlock(); }
} else {
System.out.println("Lock unavailable");
}
}
}
Explanation
Thread dumps can show threads waiting for locks and identify deadlock cycles. Tools such as jstack and Java monitoring tools help investigate stuck applications. Consistent lock ordering and short critical sections reduce risk.
Code:
public class ThreadInfoDemo {
public static void main(String[] args) {
Thread t = new Thread(() -> System.out.println("Worker running"), "worker-1");
t.start();
System.out.println("Name: " + t.getName());
System.out.println("State snapshot: " + t.getState());
}
}