There would not be any deadlock because both methods are accessing lock on Integer and String class literal in same order. So, if thread A acquires lock on Integer object , thread B will not proceed until thread A releases Integer lock, same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further.
public class DeadLockAvoid {
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(String.class){
System.out.println("Aquired lock on String.class object");
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
}
}
}
}

No comments:
Post a Comment