Assignment 9 — The bank in memory
BankLab, part 1 of 4: a bank that many threads can use at once. Accounts, deposits, withdrawals, transfers and a history, kept in memory, with a lock for each account and no deadlock.
Due Nov 3, 2026
BankLab is the last four assignments, one part a week. By the end you will have a bank server: clients connect over the network, register, log in, and move money, each client served on its own thread, and every account kept in a database so it survives a restart. This week is the bank itself, in memory, safe for many threads at once. A10 puts a server in front of it, A11 moves the accounts into a database, and A12 is all of it together. The BankLab rubric says how the finished project is assessed; this week’s work is most of its third row.
This one has its own repo. Accept it the same way you accepted A8, clone it, open the folder in IntelliJ and let it finish loading. It is laid out as A8 was: the code under src/main/java, the tests under src/test/java, and a pom.xml for JUnit. Run MemoryBankTest from the arrow beside its name. The red tests are the methods you are about to write, and a task is done when its tests are green, yours included.
What is given
Bank, an interface: the seven things a bank does. MemoryBank, the class that implements it, is yours; every method throws until you write it, and its constructor takes nothing.
void register(String name, String password) // a new account, holding 0
void login(String name, String password) // returns, or throws
long balance(String name)
void deposit(String name, long cents)
void withdraw(String name, long cents)
void transfer(String from, String to, long cents) // both change, or neither
List<Entry> history(String name) // oldest first, a copyMoney is whole cents in a long: $12.50 is 1250. A double cannot hold 0.10 exactly, and a bank that loses a cent here and there is not a bank.
Every refusal is an exception of its own, each a subclass of BankException, so a caller can tell them apart and getMessage() says what went wrong. A10’s server will turn each into an ERROR line for its client.
| thrown | when |
|---|---|
BadNameException |
a name that is empty or has a space in it |
BadPasswordException |
a password that is empty or has a space in it |
NameTakenException |
registering a name that already has an account |
NoSuchAccountException |
any name that has no account |
WrongPasswordException |
logging in with a password that is not the account’s |
BadAmountException |
an amount of 0 cents or less |
NotEnoughMoneyException |
taking out more than the account holds |
SelfTransferException |
a transfer from an account to itself |
Entry is one line of an account’s history: an id, a kind (DEPOSIT, WITHDRAWAL, TRANSFER_TO or TRANSFER_FROM), the other account of a transfer, and the amount. Finished, with equals and a toString.
One rule holds for every method: check everything before changing anything. A refused call changes no balance and adds nothing to any history, so nothing is ever half done.
Each task ends with a test of your own, at the bottom of MemoryBankTest: a case the given tests do not try, with the value worked out by hand first. It is done when it is green, and it goes red when you change the value it expects (then put it back). A refusal is tested with assertThrows, as the given loginWithAWrongPasswordThrows does.
Part 1 — one thread at a time
Accounts:
registerandlogin. A new file,src/main/java/Account.java: one account, with four fields, its name, its password, its balance in cents, and its history, aList<Entry>.MemoryBankkeeps its accounts in aMap<String, Account>from name to account.registerthrowsBadNameExceptionorBadPasswordExceptionfor a name or password that is empty or holds a space, andNameTakenExceptionfor a name already in the map; then it puts a new account in.loginthrowsNoSuchAccountExceptionfor a name not in the map, andWrongPasswordExceptionwhen the password is not the account’s. Passwords are compared exactly:Secretis notsecret.Most methods start the same way, by finding the account or throwing
NoSuchAccountException. Write that once, as a private method ofMemoryBank, and call it everywhere.Your test: registering a name that is taken throws, and the first account’s password still logs in afterwards.
balance,depositandwithdraw. An amount of 0 or less is aBadAmountException; a withdrawal of more than the balance is aNotEnoughMoneyException. Each successful deposit or withdrawal adds anEntryto the account’s history (task 4 says what goes in its id; until then any number will do).The rule that a balance never goes below 0 belongs in one place. A transfer needs it too, in task 3, so put it in
Account, in a method that throwsNotEnoughMoneyExceptionand changes nothing, and call that method from both.Your test: a withdrawal of one cent more than the balance throws, and the balance and the history are as they were.
transfer. Check in this order, and throw at the first that fails: the amount (BadAmountException); the two names,fromfirst (NoSuchAccountException); the same account twice (SelfTransferException); and last, whetherfromholds enough (NotEnoughMoneyException). Only then take the money out of one account and put it into the other.Your test: a transfer of an account’s whole balance leaves it at exactly 0, and a second transfer of one more cent throws.
history, with ids. Every transaction gets the next number from a counter the bank keeps, 1, 2, 3, …, so ids grow in the order things happened. A deposit or a withdrawal is one entry with no other account,null. A transfer is one transaction and so one id, and two entries with that id:TRANSFER_TOin the account the money left, naming the account it went to, andTRANSFER_FROMin the other, naming where it came from.historyreturns a copy:List.copyOf(...)makes one. Handing out the account’s own list would let a caller change it, and, in part 2, let another thread change it while the caller is reading.Your test: after a deposit, a withdrawal and a transfer out, an account’s history has three entries of those three kinds, oldest first, with growing ids.
Part 2 — many threads at once
A10’s server serves each client on its own thread, so every method of the bank will be called by many threads at once. Monday’s Counter lost counts when two threads ran count++ together; a balance is a count too.
Lock the account, not the bank. The simplest safe bank marks every method of MemoryBank synchronized: one lock for the whole bank, and every operation waits for every other. It is correct, and two clients moving money between four different people still take turns for no reason. Give each account a lock of its own instead, so that only operations on the same account wait for each other. This is the rubric’s difference between Good and Excellent: locking no wider than the rule it protects.
A method can hold any object’s lock, not only its own object’s, with a synchronized block:
The lock is the same one that synchronized methods of Account take, so the two can be mixed. The reading this week has the details.
One account, many threads. Make every read and every change of an account’s balance and history happen while holding that account’s lock, either in
synchronizedmethods ofAccountor insynchronized (account)blocks inMemoryBank. Inwithdraw, the check and the change go inside the same block: a check made before the block can be out of date by the time the block begins.The id counter is shared by every account, so it needs a lock too: a private
synchronizedmethod ofMemoryBankthat returns the next id.Your test: four threads each deposit 1 cent into one account 10,000 times; after all four are joined, the balance is 40,000.
A failed assertion in a thread you started does not fail the test: JUnit only sees what happens on its own thread. So a thread’s code catches what it does not expect and adds it to a list, and the test checks that list after the
joins:Transfers, many threads, and no deadlock. A transfer reads and changes two accounts, so it holds both locks, one block inside the other, while it checks and moves the money.
Taken carelessly, two locks can stop the bank for ever. One thread transfers from Alice to Bob: it takes Alice’s lock, then waits for Bob’s. At the same moment another transfers from Bob to Alice: it takes Bob’s lock, then waits for Alice’s. Each holds what the other is waiting for, and neither will ever let go. That is a deadlock: no error, no exception, the threads simply never finish.
The cure is to take the locks in the same order everywhere: whichever account’s name comes first alphabetically, its lock first.
from.compareTo(to) < 0says whetherfromcomes first. Then two transfers between the same pair, in either direction, ask for the same lock first, and one simply waits for the other.Your test: two threads, one transferring 1 cent from Alice to Bob 50,000 times, the other 1 cent from Bob to Alice 50,000 times, both starting with 1,000. A transfer refused for lack of money is fine (catch
NotEnoughMoneyExceptionand carry on). After the joins, the two balances add up to 2,000. Mark the test@Timeout(20)above@Test: a deadlocked test never finishes, and this fails it after 20 seconds instead.Done when your test is green, and goes red, or hits the timeout, when you take the locks in the order
from,toinstead (then put the order back).Registering from many threads. The map is shared too: two threads registering the same name at once must not both succeed, and two threads putting different names into a
HashMapat once can lose one of them. Guardregister, and the private method that finds an account, with the map’s lock:synchronized (accounts) { ... }, whereaccountsis the map. Hold it only while looking up or adding, and never wait for an account’s lock while holding it.Your test: two threads each register
name0toname999; every name is made exactly once, so the two threads’ successes add up to 1,000.Say what works. Fill in the section What works, and what does not in your repository’s
README.md: for each task, the names of your tests that check it, and anything you know does not work, in a sentence each. This is the rubric’s fourth row, and from A10 on it grows with the project.Done when the section names at least one test of yours for each of tasks 1 to 7.
Optional — an auditor
A bank’s auditor adds up every balance and expects the same total every time, since transfers only move money around. Add to MemoryBank
the sum of all balances at one moment, correct even while other threads are transferring. Build it in this order:
- First, the obvious version, and watch it fail. Loop over the accounts and add up their balances. Then a test: three accounts holding 1,000 each, two threads transferring between them for a while, and the main thread calling
total()over and over meanwhile, counting the times it is not 3,000. Run it: the count is not 0. Here is how: Alice holds 100 and Bobtotal()reads Alice, 100. A transfer of 50 from Alice to Bob runs.total()reads Bob, 250. The sum is 350, money that never existed. Every balance was right when it was read; they were read at different moments.
- Hold every account’s lock at once. While
total()holds all of them, no transfer can be half way. Take them in the same alphabetical order as transfers do, ortotal()and a transfer can deadlock exactly as two transfers could: sort the accounts by name into a list first. - A list of locks needs a method that calls itself. A
synchronizedblock holds one lock, and the number of accounts is not known when you write the code. So:private long sumFrom(List<Account> sorted, int i)takes the lock ofsorted.get(i)and, inside its block, returns the sum of every balance wheniis the last place, and otherwisesumFrom(sorted, i + 1). The innermost call holds every lock at once. - Copy the list of accounts before you start, under the map’s lock, so a
registerduring the count cannot change the list under you. - The test again, now with
@Timeout(20): the count of wrong totals is 0, and nothing deadlocks.
Handing in
Commit and push. The last commit before the deadline is what gets marked.
Every push is graded, one check at a time, and the result lands on your feedback pull request, so push early and read what failed rather than saving it all for the last night. The checks run your bank against cases of their own, among them eight threads on one account and eight threads transferring among five; then they run MemoryBankTest, which needs your seven tests and at least one that starts threads. A green check is a floor, not the mark: the mark is read off your code too, as the rubric’s rows describe.
A student presents this one in class on Wednesday, November 4.