Java Reference
In-Depth Information
Beware of Deadlock
Like many tasks in Java, starting a thread is easy. However, making sure your threads
play nice with the other threads in your application is often a diffi cult task in the real
world. After your threads start asking for monitor locks, you have to worry about the
possibility of deadlock. If a thread attempts to acquire a lock and, for whatever reason,
the lock never becomes available, then your thread has become deadlocked and will
never become runnable again.
For example, using the BankAccount class defi ned in this section, suppose we have the
following Teller thread that transfers $50.00 from one BankAccount object to another,
obtaining the lock of both objects before making the transfer:
public class Teller extends Thread {
private BankAccount src, dest;
public Teller(BankAccount src, BankAccount dest) {
this.src = src;
this.dest = dest;
}
public void run() {
synchronized(src) {
Thread.yield();
synchronized(dest) {
src.withdraw(50.00);
dest.deposit(50.00);
}
}
}
}
Notice the conveniently placed call to Thread.yield after the fi rst lock is acquired but
before the attempt at acquiring the second lock. You would not normally call yield here,
but I want to emphasize the importance of never knowing when a thread is preempted.
Try to determine the output of the following code:
public class DeadlockDemo {
public static void main(String [] args) {
BankAccount a = new BankAccount();
Search WWH ::




Custom Search