Java Reference
In-Depth Information
14.7. Deadlocks
Whenever you have two threads and two objects with locks, you can
have a deadlock, in which each thread has the lock on one of the objects
and is waiting for the lock on the other object. If object X has a syn-
chronized method that invokes a synchronized method on object Y, which
in turn has a synchronized method invoking a synchronized method on ob-
ject X, two threads may wait for each other to complete in order to get a
lock, and neither thread will be able to run. This situation is also called a
deadly embrace. Here's a Friendly class in which one friend, upon being
hugged, insists on hugging back:
class Friendly {
private Friendly partner;
private String name;
public Friendly(String name) {
this.name = name;
}
public synchronized void hug() {
System.out.println(Thread.currentThread().getName()+
" in " + name + ".hug() trying to invoke " +
partner.name + ".hugBack()");
partner.hugBack();
}
private synchronized void hugBack() {
System.out.println(Thread.currentThread().getName()+
" in " + name + ".hugBack()");
}
public void becomeFriend(Friendly partner) {
this.partner = partner;
}
}
 
Search WWH ::




Custom Search