How would you produce DeadLock in Java?

By | March 5, 2023

In Java, a deadlock can occur when two or more threads are blocked indefinitely, waiting for each other to release resources. Deadlocks can be produced intentionally for testing purposes, or they can occur accidentally due to a programming error.

To intentionally produce a deadlock in Java, you can create two or more threads that acquire locks in a specific order, such that each thread is waiting for a lock that is held by another thread. Here’s an example code snippet that demonstrates how to create a deadlock intentionally:

public class DeadlockExample {
private static final Object lock1 = new Object();
private 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(1000);
} 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(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println(“Thread 2 acquired lock1”);
}
}
});

t1.start();
t2.start();
}
}

In this example, two threads t1 and t2 acquire two locks lock1 and lock2 in opposite orders. This creates a situation where t1 holds lock1 and waits for lock2, while t2 holds lock2 and waits for lock1. This causes a deadlock, and both threads are blocked indefinitely.

It’s important to note that deadlocks are undesirable and can cause serious problems in a production system. Therefore, it’s always recommended to design your program in such a way that it avoids deadlocks.

You May Also Like:

What are common multi-threading issues faced by Java Developers?
What are different states of a Thread? What does those states tell us?
What happens when wait() & notify() methods are called?
What is difference between sleep(), yield() and wait() method?
What is difference between Callable and Runnable Interface?
What is difference between intrinsic synchronization and explicit locking using Lock?
What will happen when an exception arises from within a synchronized code block? Will lock be retained or released?

Leave a Reply

Your email address will not be published. Required fields are marked *