Friday, December 1, 2017

DeadLock Example In Java Threads

We generally get deadlock situations in Multithreaded applications in Java.

Here is the example , which tells in which cases we get deadlocks.

public class deadlock {
 public static void main(String[] args) { 
 
 final String s1 = "Hi";
 final String s2 = "Hello";
 
 Thread T1 = new Thread(){
  public void run(){
   synchronized (s2) {
    System.out.println("T1 Cloked on S1");
    try {
     Thread.sleep(2000);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    synchronized (s1) {
     System.out.println("T1 locked on s2");
    }
   }
  }
 };
 
 Thread T2 = new Thread(){
  public void run(){
   synchronized (s1) {
    System.out.println("T2 Locked on S2");
    try {
     Thread.sleep(2000);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    synchronized (s2) {
     System.out.println("T2 locked on s1");
    }
   }
  }
 };
 T1.start();
 T2.start();
 }

}


To avaiod deadlocks in multithreaded applications we have to maintain the locks order as below.

public class deadlock {
 public static void main(String[] args) { 
 
 final String s1 = "Hi";
 final String s2 = "Hello";
 
 Thread T1 = new Thread(){
  public void run(){
   synchronized (s2) {
    System.out.println("T1 Cloked on S1");
    try {
     Thread.sleep(2000);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    synchronized (s1) {
     System.out.println("T1 locked on s2");
    }
   }
  }
 };
 
 Thread T2 = new Thread(){
  public void run(){
   synchronized (s2) {
    System.out.println("T2 Locked on S2");
    try {
     Thread.sleep(2000);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    synchronized (s1) {
     System.out.println("T2 locked on s1");
    }
   }
  }
 };
 T1.start();
 T2.start();
 }

}

No comments: