CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 4 of 6 · 4 min read

The code

Plan, charge, dispense, and undo if the machine fails.

The account guards its own rules. The balance check and the daily limit check sit inside debit, under the same lock as the change, so two machines cannot both pass a check and overdraw (the check-then-act race of Level 5, module 3).

class Account {
    private long balance; private long withdrawnToday;

    synchronized void debit(long a, long dailyLimit) {
        if (a > balance) throw new IllegalStateException("insufficient funds");
        if (withdrawnToday + a > dailyLimit) throw new IllegalStateException("over the daily limit");
        balance -= a; withdrawnToday += a;
    }
    synchronized void undoDebit(long a) { balance += a; withdrawnToday -= a; }
}

The dispenser searches for a payout from the largest note down, backtracking when a choice leaves an amount that cannot be made. This is the same search as the change-making of module 4.

interface Dispenser {
    Optional<Map<Integer,Integer>> plan(long amount);
    void dispense(Map<Integer,Integer> plan) throws AtmException;
}

With one 500-note, three 200-notes and no 100-notes, a payout of 600 is planned as three 200-notes. A greedy method would take the 500 first and be stuck with 100 left, so the search matters.

The withdrawal runs the checks in a fixed order, and changes state only at the end:

synchronized Map<Integer,Integer> withdraw(long amount) throws AtmException {
    requireAuth();
    if (amount <= 0 || amount % 100 != 0) throw new AtmException("amount must be a multiple of 100");
    if (amount > PER_TX) throw new AtmException("over the per-transaction limit");
    Account a = bank.account(card);
    Map<Integer,Integer> plan = disp.plan(amount)
        .orElseThrow(() -> new AtmException("cannot dispense that amount"));
    try { a.debit(amount, PER_DAY); }
    catch (IllegalStateException e) { throw new AtmException(e.getMessage()); }
    try { disp.dispense(plan); }
    catch (AtmException e) {
        a.undoDebit(amount);
        throw new AtmException("machine fault, account not charged");
    }
    return plan;
}

The order is the key idea. First the cheap checks. Then the plan, which changes nothing. Then the debit, which can fail on funds or the daily limit. Then the dispense, which can fail in the hardware. If dispensing fails, the debit is reversed. This is a compensating action: the earlier step cannot be rolled back automatically, so a second step undoes it. The customer's account is never left charged for cash that did not come out.

The session methods:

synchronized String enterPin(String pin) {
    if (mode != Mode.CARD_IN) throw new IllegalStateException("no card waiting for a PIN");
    if (bank.checkPin(card, pin)) { mode = Mode.AUTH; return "welcome"; }
    tries++;
    if (tries >= 3 || bank.isBlocked(card)) { eject(); return "card blocked, keep card"; }
    return "wrong PIN, " + (3 - tries) + " left";
}

A run with a balance of 50,000, one 500-note, three 200-notes and no 100-notes (made up):

Action Result
Insert card C1, enter 0000, then 1234 "enter PIN", "wrong PIN, 2 left", "welcome"
Balance 50000
Withdraw 200 with the dispenser jammed "machine fault, account not charged", balance still 50000 and today's total 0
Withdraw 600 three 200-notes, balance 49400
Withdraw 250, 30000, 100, 0 multiple of 100; over the per-transaction limit; cannot dispense (no 100-notes left to make it); multiple of 100
Withdraw 500 one 500-note, balance 48900, today's total 1100
Account with 300, withdraw 500 "insufficient funds"
Account that has already drawn 39,800, withdraw 500 "over the daily limit"
Eject, then check the balance "card returned", then "not signed in"
Card C2, three wrong PINs "wrong PIN, 2 left", "wrong PIN, 1 left", "card blocked, keep card"
Insert C2 again "card blocked, keep card"

Compensating action

A compensating action is a later step that undoes the effect of an earlier step that cannot be rolled back automatically.

Example: crediting the account again when the dispenser jams after the debit.

Check yourself: 1. Why is the debit done after the plan and before the dispense? 2. What happens to the account when the dispenser jams? 3. Why does the limit check sit inside Account.debit?