Java Thread Deadlock - BEHIND JAVA

Java Thread Deadlock

Share This

Deadlock is a situation where two or more threads are blocked forever, waiting for each other. Here what happening is each threads are waiting to release the lock acquired by the another thread. Deadloacks happens due to improper use of synchornized block

.

Java program to acquire deadlock

In the above program you can findout that two threads named fThread and fThread started same time. So in here when fThread- enters into the run() method of FirstThread object it become generate a lock that currosponding to lockString1 in DeadlockExample class. Same time the sThread create a lock currosponding to lockString2 when it enters into the run() method of SecondThread object. Then fThread continuous its execution and prints out "Entered Into First Threads First Lock" and it wait for the lock of lockString2 in second synchronized block because it was used by sThread. The same thing happens in the case of sThread also because it wait for the lock of lockString1 which was used by fThread. So here both threads are wait for a long. the output become follows

Entered Into First Threads First Lock
Entered Into Second Threads Second Lock

How to avoid the deadlock

In the above program you can avoid the deadlock by changing synchronize block locks. Which looks like follows

No comments:

Post a Comment

Pages