#423 Code Review of a Concurrent Money Transfer

Companies:
Unknown company
Themes:
JavaConcurrencyCode Review

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

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in