Reputation: 21
I am trying to achieve deadlock condition in this program This program is not giving deadlock condition .Why? Please tell me what is the problem in this code.
The output is :
Thread1 : locked Integer
Thread2 : locked String
Thread1 : locked String
Thread2 : locked Integer
Code:
class Dead {
public void meth1() {
synchronized (Integer.class) {
System.out.println("Thread 1: locked Integer");
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e);
}
synchronized (String.class) {
System.out.println("Thread 1: locked String");
}
}
public void meth2() {
synchronized (String.class) {
System.out.println("Thread 2: locked String");
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e);
}
synchronized (Integer.class) {
System.out.println("Thread 2: locked Integer");
}
}
}
class MThread1 extends Thread {
Dead d;
MThread1(Dead d) {
this.d = d;
}
public void run() {
d.meth1();
}
}
class MThread2 extends Thread {
Dead d;
MThread2(Dead d) {
this.d = d;
}
public void run() {
d.meth2();
}
}
public class Thread1 {
public static void main(String[] args) {
// Dead d = new Dead();
MThread1 t1 = new MThread1(new Dead());
MThread2 t2 = new MThread2(new Dead());
t1.start();
t2.start();
}
}
Upvotes: 0
Views: 43
Reputation: 37023
Why would you expect it to turn into deadlock? Try following code:
//in method meth1
synchronized(Integer.class) {
//blah blah
synchronized(String.class) {
//blah blah
}
}
//in method meth2
synchronized(String.class) {
//blah blah
synchronized(Integer.class) {
//blah blah
}
}
See the way lock is being obtained here, if you try running it multiple times, you will see the deadlock.
In your case, you just get a lock on class object (while other method waiting for it) and release the lock from one method and other takes it and hence no deadlock.
Deadlock will occur when meth1
holds lock on Integer.class
and waiting to hold lock on String.class
while meth2
will hold lock on String.class
and waiting to hold lock on Integer.class
which is held by meth1
.
Upvotes: 1
Reputation: 34517
When you write
synchronized (Integer.class) {
System.out.println("Thread 1: locked Integer");
}
it locks Integer.class object and immediately unlocks it. You want this:
synchronized(Integer.class) {
System.out.println("Thread 1: locked Integer");
try {
Thread.sleep(5000);
} catch(InterruptedException e) {
System.out.println(e);
}
synchronized(String.class) {
System.out.println("Thread 1: locked String");
}
}
Upvotes: 2