Java programming language supports multithreading. It involves multiple threads running simultaneously for multitasking. But in certain cases or due to certain shortcomings, the threads find themselves in the waiting state forever. In this article, We will understand the deadlock condition in Java and different ways to avoid it. Following are the topics discussed in this blog:
What is Deadlock in Java?
Deadlock in Java is a condition where two or more threads are blocked forever, waiting for each other.
This usually happens when multiple threads need the same locks but obtain them in different orders. Multithreaded Programming in Java suffers from the deadlock situation because of the synchronized keyword.
It causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.
Deadlock Example
public
class
Example{
public
static
void
main(String[] args){
final
String r1 =
"edureka"
;
final
String r2 =
"java"
;
Thread t1 =
new
Thread() {
public
void
run(){
synchronized
(r1){
System.out.println(
"Thread 1: Locked r1"
);
try
{ Thread.sleep(
100
);}
catch
(exception e) {}
synchronized
(r2){
System.out.println(
"Thread 1: Locked r2"
);
}
}
}
};
Thread t2 =
new
Thread() {
public
void
run(){
synchronized
(r1){
System.out.println(
"Thread 2: Locked r1"
);
try
{ Thread.sleep(
100
);}
catch
(exception e) {}
synchronized
(r2){
System.out.println(
"Thread 2: Locked r2"
);
}
}
}
};
t1.start();
t2.start();
}
}
Output: Thread 1: Locked r1 Thread 2: Locked r2
A deadlock occurs when two or more threads in the JVM form a cyclic dependency with each other. In this illustration ‘thread 2’ is in a wait state, waiting on
Resource A owned by ‘thread 1’, while ‘thread 1’ is in a wait state, waiting on Resource B owned by ‘thread 2’. In such a condition, these two threads are ‘hanging’ indefinitely without making any further progress. This results in an “application hang” where the application process is running but the system is not responding to user requests.
How To Avoid Deadlock in Java?
Although it is not completely possible to avoid deadlock condition, but we can follow certain measures or pointers to avoid them: