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^121 <= 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.