Java Reference
In-Depth Information
the program to prevent overlapping of operations on the same account, and this is where declaring blocks
of code to be synchronized on a particular object can help.
Let's consider the methods in the class Bank once more. What you really want is the code in the doTrans-
action() method to be synchronized so that simultaneous processing of the same account is prevented,
not so that processing of different accounts is inhibited. What you need to do is synchronize the process-
ing code for a transaction on the Account object that is involved.
TRY IT OUT: Applying Synchronized Code Blocks
You can do this with the following changes:
public class Bank {
// Perform a transaction
public void doTransaction(Transaction transaction) {
switch(transaction.getTransactionType()) {
case CREDIT:
synchronized(transaction.getAccount()) {
// Get current balance
int balance = transaction.getAccount().getBalance();
// Credits require a lot of checks...
try {
Thread.sleep(100);
} catch(InterruptedException e) {
System.out.println(e);
}
balance += transaction.getAmount(); //
Increment the balance
transaction.getAccount().setBalance(balance); // Restore
A/C balance
break;
}
case DEBIT:
synchronized(transaction.getAccount()) {
// Get current balance
int balance = transaction.getAccount().getBalance();
// Debits require even more checks...
try {
Thread.sleep(150);
} catch(InterruptedException e) {
System.out.println(e);
}
balance -= transaction.getAmount(); //
Search WWH ::




Custom Search