G52CON: Solution to Exercise 4, Monitors in Java

  1. A savings account is shared by several people. Each person may deposit or withdraw money from the account. The current balance in the account is the sum of all deposits to date less the sum of all withdrawals to date. The balance must never become negative. Account holders are represented as processes. A process making a deposit never has to delay (except for mutual exclusion), but a withdrawal has to wait until there are sufficient funds.

    Develop a Java class to solve this problem (i.e. translate the monitor solution to exercise 4 into Java). In addition to the constructor, the class should have two public methods: deposit(int amount) and withdraw(int amount). Assume the arguments to deposit and withdraw are postive.


class SavingsAccount {

    protected long balance;

    public SavingsAccount(long openingBalance) {
        balance = openingBalance;
    }

    public synchronized void deposit(int amount) {
        balance += amount;
        notifyAll();
    }

    public synchronized withdraw(int amount) throws InterruptedException {
        while (amount > balance)
            wait();
        balance -= amount;
    }
}

The solution is very similar to that using monitors. The current balance is held in the private integer field, balance. Mutual exclusion is explicit and indicated by the synchronized keyworld; condition synchronisation is achieved using wait and notifyAll, the latter being used to indicate that funds have been deposited.


Copyright © 2006 Brian Logan

This file is maintained by Brian Logan
Last modified: 17:37, 13-Mar-2007