«Back to Home

Core Java

Topics

Deadlock In Java

Deadlock
 
In Java, deadlock is a part of multithreading. Deadlock can arise in a situation when a thread is waiting for an object lock, that is obtained by another thread and second thread is waiting for an object lock that is obtained by first thread. As both threads are waiting for each other to free the lock, the condition is called a deadlock.
 
Let’s see an example, given below.
 
Code
  1. public class DeadLock {  
  2.     public static void main(String[] args) {  
  3.         final String s1 = "James";  
  4.         final String s2 = "Harry";  
  5.         Thread t1 = new Thread() {  
  6.             public void run() {  
  7.                 synchronized(s1) {  
  8.                     System.out.println(" s1 locked ");  
  9.                     try {  
  10.                         Thread.sleep(1500);  
  11.                     } catch (Exception e) {}  
  12.                     synchronized(s2) {  
  13.                         System.out.println(" s2 locked ");  
  14.                     }  
  15.                 }  
  16.             }  
  17.         };  
  18.         Thread t2 = new Thread() {  
  19.             public void run() {  
  20.                 synchronized(s2) {  
  21.                     System.out.println(" s2 locked... ");  
  22.                     try {  
  23.                         Thread.sleep(1500);  
  24.                     } catch (Exception e) {}  
  25.                     synchronized(s1) {  
  26.                         System.out.println(" s1 locked... ");  
  27.                     }  
  28.                 }  
  29.             }  
  30.         };  
  31.         t1.start();  
  32.         t2.start();  
  33.     }  
  34. }  
21
22

Output

23

Summary

Thus, we learnt that In Java, deadlock is a part of multithreading and it can arise in a situation when a thread is waiting for an object lock.