Deadlock in Java

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Deadlock in java

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.

Deadlock in java

Example of Deadlock in java

  1. public class TestDeadlockExample1 {  
  2.   public static void main(String[] args) {  
  3.     final String resource1 = "ratan jaiswal";  
  4.     final String resource2 = "vimal jaiswal";  
  5.     // t1 tries to lock resource1 then resource2  
  6.     Thread t1 = new Thread() {  
  7.       public void run() {  
  8.           synchronized (resource1) {  
  9.            System.out.println("Thread 1: locked resource 1");  
  10.   
  11.            try { Thread.sleep(100);} catch (Exception e) {}  
  12.   
  13.            synchronized (resource2) {  
  14.             System.out.println("Thread 1: locked resource 2");  
  15.            }  
  16.          }  
  17.       }  
  18.     };  
  19.   
  20.     // t2 tries to lock resource2 then resource1  
  21.     Thread t2 = new Thread() {  
  22.       public void run() {  
  23.         synchronized (resource2) {  
  24.           System.out.println("Thread 2: locked resource 2");  
  25.   
  26.           try { Thread.sleep(100);} catch (Exception e) {}  
  27.   
  28.           synchronized (resource1) {  
  29.             System.out.println("Thread 2: locked resource 1");  
  30.           }  
  31.         }  
  32.       }  
  33.     };  
  34.   
  35.       
  36.     t1.start();  
  37.     t2.start();  
  38.   }  
  39. }  
  40.           
Output: Thread 1: locked resource 1
        Thread 2: locked resource 2