Java Reference
In-Depth Information
Running the Example
Now, if you run the example, the final balance will be wrong. You should get results something like
the following:
Original balance : $500
Total credits : $1252
Total debits : $921
Final balance : $89
Should be : $831
Of course, your results won't be the same as this, but they should be just as wrong. The customer will
not be happy. His account balance is seriously out - in the bank's favor, of course, as always. So how
has this come about?
The problem is that both clerks are operating on the same account at the same time. Both clerks call the
doTransaction() method for the Bank object, so this method is executed by both clerk threads.
Separate calls on the same method are overlapping.
Try It Out - Synchronizing Methods
One way we can fix this is by simply declaring the method that operates on an account as
synchronized . This will prevent one clerk getting at it while it is still in progress with the other clerk.
To implement this you should amend the Bank class definition as follows:
// Define the bank
class Bank {
// Perform a transaction
synchronized public void doTransaction(Transaction transaction) {
// Code exactly as before...
}
}
How It Works
Declaring this method as synchronized will prevent a call to it from being executed while another is
still in operation. If you run the example again with this change, the result will be something like:
Original balance : $500
Total credits : $1201
Total debits : $931
Final balance : $770
Should be : $770
The amounts may be different because the transaction amounts are random, but your final balance
should be the same as adding the credits to the original balance and subtracting the debits.
Search WWH ::




Custom Search