Introduction
Multithreading is one of Java’s most powerful features, enabling applications to perform multiple tasks simultaneously. While multithreading improves performance and responsiveness, it also introduces several challenges, such as race conditions, thread interference, starvation, and deadlocks.
A deadlock occurs when two or more threads become permanently blocked because each thread is waiting for a resource held by another thread. Since none of the threads can proceed, the application stops making progress, even though it is still running.
What is Java Deadlock?
A Java Deadlock is a situation in which two or more threads are blocked forever because each thread is waiting for a lock that is currently held by another thread.
Since none of the threads can acquire the required lock, they remain blocked indefinitely, causing the application to stop progressing.
For example:
- Thread A holds Lock 1 and waits for Lock 2.
- Thread B holds Lock 2 and waits for Lock 1.
Neither thread can continue, resulting in a deadlock.
How Deadlock Occurs
Consider two shared resources:
- Lock A
- Lock B
The following sequence can create a deadlock:
- Thread 1 acquires Lock A.
- Thread 2 acquires Lock B.
- Thread 1 tries to acquire Lock B.
- Thread 2 tries to acquire Lock A.
- Both threads wait forever.
This circular dependency prevents either thread from completing.
Syntax Example
The following code demonstrates a deadlock.
class Shared {
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 acquired LOCK1");
try {
Thread.sleep("111");
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (LOCK2) {
System.out.println("Thread 1 acquired LOCK2");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (LOCK2) {
System.out.println("Thread 2 acquired LOCK2");
try {
Thread.sleep("111");
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (LOCK1) {
System.out.println("Thread 2 acquired LOCK1");
}
}
});
t1.start();
t2.start();
}
}
Possible Output
Thread 1 acquired LOCK1
Thread 2 acquired LOCK2
The program appears to freeze because:
- Thread 1 waits for LOCK2.
- Thread 2 waits for LOCK1.
Neither lock is released, so both threads remain blocked forever.
Four Necessary Conditions for Deadlock
A deadlock occurs only when all four of the following conditions are true.
1. Mutual Exclusion
A resource can be used by only one thread at a time.
Example:
synchronized(lock) {
}
2. Hold and Wait
A thread holds one resource while waiting for another.
Example:
- Thread holds Lock A.
- Thread waits for Lock B.
3. No Preemption
A lock cannot be forcibly taken away from a thread.
The thread must release it voluntarily.
4. Circular Wait
Two or more threads form a cycle where each waits for a resource held by another thread.
Example:
Thread A → Lock B
Thread B → Lock C
Thread C → Lock A
Breaking any one of these four conditions prevents a deadlock.
Real-Life Example
Imagine two cars meeting on a one-lane bridge.
- Car A enters from the left.
- Car B enters from the right.
- Neither driver wants to reverse.
- Both cars block each other.
- Traffic stops completely.
This is similar to a Java deadlock.
- Cars = Threads
- Bridge = Shared resource
- Waiting = Threads waiting for locks
- Traffic jam = Deadlock
Deadlock Example with Bank Accounts
Suppose a banking application transfers money between two accounts.
synchronized(account1) {
synchronized(account2) {
// Transfer money
}
}
Another thread performs:
synchronized(account2) {
synchronized(account1) {
// Transfer money
}
}
If both transfers start simultaneously:
- First thread locks Account 1.
- Second thread locks Account 2.
- Each waits for the other’s lock.
A deadlock occurs.
How to Prevent Deadlock
1. Acquire Locks in a Consistent Order
Always acquire multiple locks in the same order.
Correct:
synchronized(lock1) {
synchronized(lock2) {
}
}
Every thread should follow the same lock sequence.
2. Minimize Synchronized Blocks
Keep synchronized code as short as possible.
Instead of:
synchronized(lock) {
calculate();
print();
save();
}
Synchronize only the code that truly accesses shared data.
3. Avoid Nested Locks
Nested synchronization increases the risk of deadlocks.
Try to redesign code to reduce lock nesting.
4. Use Lock Timeouts
The ReentrantLock class allows timed lock attempts.
Example:
if(lock.tryLock()) {
try {
// Critical section
} finally {
lock.unlock();
}
}
Or:
if(lock.tryLock(2, TimeUnit.SECONDS)) {
try {
// Critical section
}
finally {
lock.unlock();
}
}
If the lock cannot be obtained within the timeout, the thread can take another action instead of waiting forever.
5. Use High-Level Concurrency Utilities
Instead of manually synchronizing everything, consider utilities from the java.util.concurrent package, such as:
- ReentrantLock
- Semaphore
- CountDownLatch
- CyclicBarrier
- BlockingQueue
- ExecutorService
These utilities often simplify concurrency and reduce the risk of deadlocks.
Detecting Deadlocks
Java provides several ways to detect deadlocks.
Using Thread Dumps
Generate a thread dump with tools such as:
jstack
or
jcmd
If a deadlock exists, the dump typically reports the threads involved and the locks they are waiting for.
Using Visual Monitoring Tools
You can detect deadlocks using tools like:
- JConsole
- VisualVM
- Java Mission Control
These tools display thread states, monitor ownership, and blocked threads, making deadlocks easier to diagnose.
Deadlock vs Starvation
| Feature | Deadlock | Starvation |
|---|---|---|
| Cause | Circular waiting | Thread never gets CPU time or a required resource |
| Threads Blocked | Yes | Not necessarily |
| Progress | Stops completely | Some threads continue |
| Recovery | Usually requires intervention | Often resolved by improving scheduling or fairness |
Deadlock vs Livelock
| Feature | Deadlock | Livelock |
|---|---|---|
| Threads Blocked | Yes | No |
| Threads Running | No | Yes |
| Progress | None | None |
| Cause | Waiting for locks | Threads repeatedly react to each other without completing work |
Common Mistakes
1. Acquiring Locks in Different Orders
Incorrect:
Thread A:
synchronized(lock1) {
synchronized(lock2) {
}
}
Thread B:
synchronized(lock2) {
synchronized(lock1) {
}
}
This is one of the most common causes of deadlocks.
2. Overusing Synchronization
Synchronizing every method or large code blocks increases contention and the possibility of deadlocks.
3. Holding Locks Longer Than Necessary
Perform lengthy calculations, file operations, or network calls outside synchronized blocks whenever possible.
4. Ignoring Nested Synchronization
Multiple nested locks make applications more complex and increase the likelihood of circular waiting.
5. Not Testing Concurrent Code
Concurrency bugs may appear only under heavy load or specific timing conditions.
Always test multithreaded code thoroughly.
Best Practices
- Acquire multiple locks in a consistent order.
- Keep synchronized blocks as small as possible.
- Avoid unnecessary nested locks.
- Use ReentrantLock with tryLock() when appropriate.
- Prefer concurrency utilities from java.util.concurrent.
- Release resources promptly.
- Review synchronization design during code reviews.
- Use thread dumps and monitoring tools to investigate blocked threads.
- Stress-test multithreaded applications before deployment.
Conclusion
Java Deadlock is a serious multithreading issue that occurs when two or more threads wait indefinitely for resources held by one another. Deadlocks can make applications appear frozen, reduce system reliability, and be difficult to debug.
By understanding the causes of deadlocks, following consistent lock ordering, minimizing synchronized sections, avoiding unnecessary nested locks, and using modern concurrency utilities, developers can significantly reduce the risk of deadlocks in Java applications.