What is deadlock in Java and how can it be avoided?
A deadlock is a situation where two or more threads are permanently blocked, each waiting to acquire a lock held by another thread in the cycle. No thread can proceed, and the application hangs indefinitely without throwing an exception.
The classic example: Thread A holds Lock 1 and waits for Lock 2. Thread B holds Lock 2 and waits for Lock 1. Neither can proceed.
Four conditions must all hold simultaneously for a deadlock (Coffman conditions): 1. **Mutual exclusion**: at least one resource is held in non-shareable mode. 2. **Hold and wait**: a thread holds one resource while waiting for another. 3. **No preemption**: the OS cannot forcibly take a lock from a thread. 4. **Circular wait**: a circular chain of threads each waiting on the next.
Prevention strategies target breaking one of these conditions:
**Lock ordering**: All threads acquire locks in the same global order. If every thread always acquires Lock 1 before Lock 2, circular wait is impossible. This is the most common and effective prevention technique.
**Try-lock with timeout**: Use `ReentrantLock.tryLock(timeout, unit)`. If a thread cannot acquire a lock within the timeout, it releases all held locks and retries or backs off. This breaks hold-and-wait.
**Lock-free data structures**: Use `AtomicReference`, `ConcurrentHashMap`, and other CAS-based structures that need no traditional locking.
**Deadlock detection**: In production, thread dumps via `jstack` or JMX expose deadlocked threads. The JVM can detect deadlock in thread dumps and reports the cycle. Tools: Java Flight Recorder, VisualVM.
**Avoid nested locking**: Minimize acquiring multiple locks simultaneously. If unavoidable, use a well-documented global ordering.
Deadlock is distinct from livelock (threads keep changing state but make no progress) and starvation (a thread is perpetually denied access but other threads make progress).
Explains deadlock with a concrete two-thread example, names at least two Coffman conditions, and describes lock ordering as a prevention strategy.
Also names all four Coffman conditions, covers try-lock timeout strategy, distinguishes deadlock from livelock and starvation, and mentions detection tools like jstack or JMX.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment