Java Reference
In-Depth Information
Figure 15.10 The bank account is now thread-safe, and deposits and withdrawals are
successful, even in a multithreaded application.
There are two things you will notice about running the SomethingsFixed
program: It takes longer to run and it works this time. This is because the
deposits and withdrawals are not occurring at the same time as they were in the
SomethingsWrong program, but rather they are executing sequentially (one at
a time). Figure 15.10 shows the output of the SomethingsFixed program.
Deadlock Issues
Well, if you were dangerous after learning how to create a thread, you are
probably just as dangerous now that I have shown you the synchronized key-
word. Before synchronizing, our program's data was being corrupted. After
synchronizing, our program now becomes susceptible to deadlock , which
occurs when a thread is waiting for a lock that never becomes available.
There are ways to avoid deadlock, including ordering locks and using the
wait() and notify() methods, both of which I will discuss. However, let me
show you a simple but realistic example of how deadlock can occur. The fol-
lowing LazyTeller class contains a transfer() method that transfers money
from one bank account to another. In order to transfer money, the teller needs
the lock on both accounts to ensure that the transaction is successful. Study the
transfer() method and see if you can predict where a problem might arise:
public class LazyTeller extends Thread
{
private ThreadSafeBankAccount source, dest;
public LazyTeller(ThreadSafeBankAccount a, ThreadSafeBankAccount b)
{
source = a;
dest = b;
}
public void run()
{
transfer(250.00);
}
public void transfer(double amount)
Search WWH ::




Custom Search