0

In this code two objects of DeadLock d1 and d2 is created then separate copy of all resources i.e., r1,r2,r3 will be created for d1 and d2 even then threads d1 and d2 enter deadlock while accessing the resources what is the reason can anyone please explain it correctly

import java.util.*;
class DeadLock extends Thread{
String r1="Oracle";
String r2="Sybase";
String r3="DB2";
DeadLock(String name){
    super(name);
}
public void run(){
    if(Thread.currentThread().getName().equals("Rama")){
        acquireRamaResources();
    }
    else{
        acquireSitaResources();
    }
}
void acquireRamaResources(){
    synchronized(r1){
        System.out.println("Rama acquired Oracle");
        synchronized (r2){
            System.out.println("Rama acquired Sybase");
            synchronized(r3){
                System.out.println("Rama acquired DB2");
            }
        }
    }
}
void acquireSitaResources(){
    synchronized(r3){
        System.out.println("Sita acquired DB2");
        synchronized (r2){
            System.out.println("Sita acquired Sybase");
            synchronized(r1){
                System.out.println("Sita acquired Oracle");
            }
        }
    }
  }
}

class Demo{
public static void main(String[]args){
    DeadLock d1=new DeadLock("Rama");
    DeadLock d2=new DeadLock("Sita");
    d1.start();
    d2.start();
 }
}
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49

1 Answers1

0

This is because r1, r2 and r3 fields have same values (same objects). In short, when you use literal strings in Java, then they are taken from special pool.

If you change you code in the following way

String r1=new String("Oracle");
String r2=new String("Sybase");
String r3=new String("DB2");

deadlock will dissapear, because values of that fields will be different objects (new String() call creates different objects).

The following code prints true, then false.

    String a = "asdasdas";
    String b = "asdasdas";
    System.out.println(a == b);
    a = new String("asdasdas");
    b = new String("asdasdas");
    System.out.println(a == b);

You may want to check this fore more info

Andrey Cheboksarov
  • 649
  • 1
  • 5
  • 9