Java Reference
In-Depth Information
Should be : $915
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 off — 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 you can fix this is by simply declaring the method that operates on an account as synchron-
ized . This prevents one clerk getting at the method for an account 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
public class Bank {
// Perform a transaction
synchronized public void doTransaction(Transaction transaction) {
// Code exactly as before...
}
}
Directory "BankOperation 2 - Synchronized Methods"
How It Works
Declaring this method as synchronized prevents a call to it from being executed while another is still in
operation. If you run the example again with this change, the result is something like:
Original balance : $500
Total credits : $1279
Total debits : $932
Final balance : $847
Should be : $847
The amounts might 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.
As you saw earlier, when you declare methods in a class as synchronized , it prevents concurrent ex-
ecution of those methods within a single object, including concurrent execution of the same method . It
is important not to let the fact that there is only one copy of a particular method confuse you. A given
method can be potentially executing in any number of threads — as many threads as there are in the pro-
gram, in fact. If it were not synchronized, the doTransaction() method could be executed concurrently
by any number of clerks.
Search WWH ::




Custom Search