Transfer hangs between accounts
Review this Java account-transfer method.
What a strong answer looks like
Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.
0:00 of about 32 min
Mark a line and say what kind of problem it is.0 findings
1class Account {
2 private long balance;
3 final Object lock = new Object();
4 long balance() { synchronized (lock) { return balance; } }
5 void credit(long a) { synchronized (lock) { balance += a; } }
6 void debit(long a) { synchronized (lock) { balance -= a; } }
7}
8
9void transfer(Account from, Account to, long amount) {
10 synchronized (from.lock) {
11 synchronized (to.lock) {
12 from.debit(amount);
13 to.credit(amount);
14 }
15 }
16}
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.
Run or narrate your approach, then ask the coach.