Implementing a Thread-Safe Bank Account Transfer System

Implementing a Thread-Safe Bank Account Transfer System

In this lesson, we will build a thread-safe bank account transfer system. You’ll learn how to use synchronization in Java to manage concurrent operations on shared resources like bank accounts, and how to prevent deadlocks using ordered resource acquisition.

What You'll Learn

By the end of this lesson, you will:

  • Understand how to implement a thread-safe system for transferring money between bank accounts.
  • Learn how to apply synchronization to protect shared resources.
  • Explore how to avoid deadlock conditions by controlling the order of resource acquisition.

This lesson will guide you through writing Java code that safely transfers money between bank accounts while ensuring that no race conditions or deadlocks occur, even in a multi-threaded environment.

Thread-Safe Bank Account Transfers

Imagine a banking system where clients transfer money between accounts concurrently. Without proper thread safety, multiple threads could attempt to modify the same account simultaneously, leading to race conditions and inconsistent balances.

To solve this, we use synchronization to control access to shared resources. When one thread transfers money between two accounts, it must ensure that no other thread can access those accounts until the transfer is complete.

Implementing the BankAccount Class

The BankAccount class represents a single account in the bank. We will synchronize the operations on this account to ensure that its state (balance) is not corrupted when accessed by multiple threads.

Java
public class BankAccount {
    private final int id;
    private int balance;

    public BankAccount(int id, int balance) {
        this.id = id;
        this.balance = balance;
    }

    public int getId() {
        return id;
    }

Each BankAccount object has an id and a balance. The id is a unique identifier for the account, and the balance keeps track of the money in the account. These fields are important for ensuring that transfers happen between the correct accounts and that balances are updated accurately.

Java
    public void deposit(int amount) {
        balance += amount;
    }

    public boolean withdraw(int amount) {
        if (balance < amount) return false;
        balance -= amount;
        return true;
    }

The deposit method adds money to the balance, and the withdraw method subtracts money if sufficient funds are available. Both methods modify the balance field, so we need to ensure that no two threads can change the balance at the same time. This will be handled by synchronization in the transfer method.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal