AlgoMaster Logo
AlgoMasterDesign a Thread-Safe Bank Accountmedium

Design a Thread-Safe Bank Account

medium

Design a bank account whose balance can be accessed safely by many threads.

Implement the BankAccount class:

  • BankAccount(initialBalance) creates an account with the given balance.
  • deposit(amount) adds amount to the balance.
  • withdraw(amount) subtracts amount and returns true if sufficient funds are available. Otherwise, it leaves the balance unchanged and returns false.
  • getBalance() returns the current balance.

Every operation must be thread-safe and linearizable. In particular, checking the balance and subtracting a withdrawal must be one atomic operation. Concurrent withdrawals must never make the balance negative.

Different BankAccount instances must synchronize independently. The judge creates all customer threads; your class should protect its state rather than create threads itself.

Standard concurrency and thread APIs are preloaded, so you do not need import, include, package, or using statements.

Example 1:

Input:

Output:

Explanation: The first withdrawal succeeds. Only 120 remains, so the second withdrawal is rejected without changing the balance.

Example 2:

Input:

Output:

Constraints

  • 0 <= initialBalance <= 10^12
  • 1 <= amount <= 10^9
  • At most 100000 operations are performed per account.
  • The balance always fits in a signed 64-bit integer.
  • Every method may be called concurrently.
Loading...

Input

account = BankAccount(100)
account.deposit(50)
account.withdraw(30)
account.withdraw(150)
account.getBalance()

Output

[true, false, 120]

Run is a quick check against the first couple of scenarios, which is roughly what these examples describe. Submit puts your class under the full set, which stays hidden.