/* This class is not correct. It needs to be fixed to work in a * sequential setting, and also a multithreaded setting. What must we * do to change it? */ public class BankAccount { private static int totalTransfers = 0; // guarded by xferLock private static Object xferLock = new Object(); private double balance; // guarded by this public BankAccount(double initialBalance) { this.balance = initialBalance; } synchronized public void withdraw(double amount) { balance -= amount; } synchronized public void deposit(double amount) { balance += amount; } /* synchronized */ public void transfer(double amount, BankAccount other) { // Uncommenting the above is redundant, and in fact can lead to deadlock! // In particular, if ba1 is one BankAccount and ba2 is another, than if one thread // does ba1.transfer(0.0,ba2) and another thread does ba2.transfer(0.0,ba1), // the two threads could deadlock this.withdraw(amount); other.deposit(amount); synchronized (xferLock) { totalTransfers ++; } } synchronized public double getBalance() { return balance; } public static int getTotalTransfers() { synchronized (xferLock) { return totalTransfers; } } }