I have three classes below. Main, two threads and Obj whose methods are synchronized
public class DeadLocks {
public static void main(String[] args) {
SyncObj so = new SyncObj();
ThreadObj to = new ThreadObj(so);
ThreadObj1 to1 = new ThreadObj1(so);
to.start();
to1.start();
}
}
class SyncObj {
synchronized void foo() {
System.out.println("Foo Started");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bar();
}
synchronized void bar() {
System.out.println("bar started");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
foo();
}
}
class ThreadObj1 extends Thread {
SyncObj so;
public ThreadObj1(SyncObj so) {
this.so = so;
}
@Override
public void run() {
so.bar();
}
}
class ThreadObj extends Thread {
SyncObj so;
public ThreadObj(SyncObj so) {
this.so = so;
}
@Override
public void run() {
so.foo();
}
}
In the above code I'm calling synchronized methods on the same object. Both the methods are executing and calling each other simultaneously.There is no deadlock situation. Could anyone explain why? sorry for such a silly question.
As far as I can see, you are using the same object (so) for both the cases. So there is no case for a deadlock. You would need to lock on two or more objects wherein each critical section requires the lock other than the one that it is holding. That other lock is held by "another" thread.
Confusing, this will enlighten: "https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html"
You would never ever deadlock in a scenario that you describe. In this scenario there is only one so that is being shared and is being synchronized with.
Let me give you an example to illustrate:
Suppose Andy and Sandy are playing with two soccer balls B1 and B2.
Now further suppose that both Andy and Sandy have balls B1 and B2 in their possession respectively. For example Andy has ball B1 and Sandy has ball B2.
Now they devise a game wherein they need both the balls each. Now Sandy wants ball B1 as well and at the same time, Andy wants B2.
And both of them cannot relinquish the balls that they hold. Andy will not give up B1 and vice-versa.
So both of them cannot continue and are stuck. We call this a deadlocked situation.
Hope this example helps. You could use your imagination to increase the number of balls in play to 3 or 4 (and so on..) and / or increase the number of players.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With