The following class is example of a java program which leads to a deadlock. Basically a person a is bowing to his friend b. and b in turn bows back to friend a. The problem is Person a and Person b both have obtained lock on their objects. When person b tries to bowback to a and at the same time, a tries to bowback to person b. In this case, both will wait endlessly to obtain a lock to bow to each other. This situation is refered as deadlock.
class Person extends Thread {
protected String myName;
Person friend;
public Person(String name)
{
super(name);
myName=name;
//do nothing
}
public synchronized void bow()
{
System.out.println(myName+" is bowing to "+friend.toStr());
friend.bowBack();
}
public synchronized void bowBack()
{
System.out.println(myName+" is bowing back to " +friend.toStr());
}
public void setFriend(Person p)
{
this.friend=p;
}
public String toStr()
{
return myName;
}
public void run() {
bow();
}
}
public class Deadlock {
public static void main(String[] args) {
Person a=new Person("A");
Person b=new Person("B");
a.setFriend(b);
b.setFriend(a);
a.start();
b.start();
}
}
There are various techniques by which you can synchronize sequence of events.
In the above example, instead of synchronizing the entire method, just synchronize a block, so that the deadlock doesn't happen.
E.g,
public void bow()
{
Synchronized(this) {
System.out.println(myName+" is bowing to "+friend.toStr());
}
friend.bowBack();
}
public synchronized void bowBack()
{
Synchronized(this) {
System.out.println(myName+" is bowing back to " +friend.toStr());
}
}
No comments:
Post a Comment