Thursday, 14 July 2016

Java Code to Create Dead Lock

If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock because if thread 1 acquires lock on Sting object while executing method1() and thread 2 acquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen. 


public class DeadLockDemo {
public void method1(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
}
}
}
public void method2(){
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
}

No comments:

Post a Comment