#423 Code Review of a Concurrent Money Transfer
Check whether the implementation is correct for multithreaded use and identify problems in the code:
public class TransferProblem {
public class Account {
final long id;
BigDecimal balance;
BigDecimal maxBalance;
public Account(
final long id,
final BigDecimal balance,
final BigDecimal maxBalance
) {
this.id = id;
this.balance = balance;
this.maxBalance = maxBalance;
}
}
public boolean transferMoney(
final Account src, final Account dst, final BigDecimal value
) {
if (value.compareTo(BigDecimal.ZERO) < 0) {
return false;
}
synchronized (src) {
synchronized (dst) {
if (src.balance.compareTo(value) < 0) {
return false;
}
if (
(dst.balance.add(value)).compareTo(dst.maxBalance) > 0
) {
return false;
}
src.balance = src.balance.subtract(value);
dst.balance = dst.balance.add(value);
}
}
return true;
}
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor