In this write-up, we are going to learn the below-listed aspects of deadlocks in java:
- What is a Deadlock?
- When and Where a Deadlock can occur
- Examples of Deadlock
- How to Prevent a Deadlock in Java
So let’s start!
What is a Deadlock?
Deadlock describes a situation where two more threads are trying to access the same resource simultaneously and as a result, no one gets the resource and is eventually blocked forever.
When and Where a Deadlock can occur
In java, the deadlock scenario can occur only in the multithreaded environment where more than one thread executes at the same time. Moreover, a synchronized keyword can cause a deadlock in java.
From the above figure, we can observe that thread1 is waiting for thread2 to release the resources and vice versa.
Examples of Deadlock
Let’s consider the below-given example for a profound understanding of how a deadlock occurs in java:
public static void main(String[] args) {
final String res1 = "First Resource";
final String res2 = "Second Resource";
Thread thread1 = new Thread() {
public void run() {
synchronized (res1) {
System.out.println("Thread 1: locked the res1");
try {
Thread.sleep(2000);
} catch (Exception excep) {
}
synchronized (res2) {
System.out.println("Thread 1: locked the res2");
}
}
}
};
Thread thread2 = new Thread() {
public void run() {
synchronized (res2) {
System.out.println("Thread 2: locked the res2");
try {
Thread.sleep(2000);
} catch (Exception excep) {
}
synchronized (res1) {
System.out.println("Thread 2: locked the res1");
}
}
}
};
thread1.start();
thread2.start();
}
}
In this example, we have two threads thread1 and thread2, both the threads start and call the run() method.
Following will be the output for the above snippet:
From the above snippet, it is clear that both the threads locked each other.
How to Prevent a Deadlock in Java
Below is the list of preventions that can be adopted to avoid a deadlock in java:
- Avoid the use of nested and unnecessary locks.
- Acquire the locks in the same order.
- Use Thread Joins to avoid the Deadlock i.e., release a lock after a timeout period.
Conclusion
Deadlock describes a situation where two more threads are trying to access the same resource simultaneously and as a result, no one gets the resource and is eventually blocked forever. In java, a deadlock occurs only in the multithreaded environment where more than one thread executes at the same time. Moreover, a synchronized keyword can cause a deadlock in java. In java, a deadlock can’t be resolved completely however, it can be avoided by adopting some necessary precautions/rules e.g. avoiding the use of unnecessary locks, nested locks, etc.
This write-up presents a detailed overview of what are deadlocks in java, how deadlocks occur, and how to avoid the deadlocks in java.