Deadlock in Java Multithreading and Prevention Strategies
Deadlock in Java Multithreading and Prevention Strategies
1. What is Deadlock?
A deadlock is a situation in Java multithreading where two or more threads are blocked forever,
waiting for each other to release a resource. This happens when multiple threads hold some shared
resources and wait indefinitely for other resources held by other threads.
2. Hold and Wait → A thread holds a resource and waits for another.
class Resource {
synchronized (this) {
synchronized (otherResource) {
thread1.start();
thread2.start();
class SafeResource {
synchronized (this) {
Ensures that Thread-1 and Thread-2 acquire locks in the same sequence, preventing circular
wait.
2. Use Try-Lock Instead of Synchronized (Avoid Waiting Forever)
Use tryLock() from ReentrantLock instead of synchronized, so threads do not wait indefinitely.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ResourceSafe {
void safeMethod() {
while (true) {
if (lock1.tryLock()) {
try {
if (lock2.tryLock()) {
try {
break;
} finally { lock2.unlock(); }
} finally { lock1.unlock(); }
t1.start();
t2.start();
If a thread cannot acquire both locks, it releases the first lock and retries, avoiding deadlock.
If a thread cannot acquire a lock within a set time, it backs off and retries later.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.TimeUnit;
class TimeoutResource {
void safeMethod() {
try {
if (lock1.tryLock(100, TimeUnit.MILLISECONDS)) {
try {
if (lock2.tryLock(100, TimeUnit.MILLISECONDS)) {
try {
} finally { lock2.unlock(); }
} finally { lock1.unlock(); }
} else {
t1.start();
t2.start();
If a thread cannot acquire both locks within 100ms, it retries later, preventing deadlock.
If possible, use one lock for all resources instead of multiple locks.
import java.util.concurrent.locks.ReentrantLock;
class SingleLockResource {
void method() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " is executing.");
} finally {
lock.unlock();
t1.start();
t2.start();
Since both threads use the same lock, deadlock cannot occur.
Single Lock
Use one lock instead of multiple locks Prevents circular wait
Approach
Do not hold one lock while waiting for Reduces risk but not always
Avoid Nested Locks
another possible
6. Conclusion
• Deadlock is a critical issue in Java multithreading that occurs when threads wait indefinitely
for each other.
• Prevention strategies like lock ordering, tryLock, timeouts, and single locks help avoid
deadlocks.
Would you like a real-world example, such as preventing deadlocks in a banking transaction
system?