Computer scienceProgramming languagesJavaWorking with dataMultithreadingSynchronization

Atomics

Bank account

Report a typo

Create a simple, thread-safe BankAccount class that uses an AtomicLong to represent the account balance. Implement methods for depositing, withdrawing, and checking the balance, ensuring that these operations are atomic and safe from race conditions when accessed by multiple threads. The withdrawal method must subtract the given amount if there is a sufficient amount on the balance and return true, otherwise return false and leave the balance unchanged.

In the output, we check the balance after each action described in the input.

Sample Input 1:

Initialize account with balance: 1000
Deposit: 500
Withdraw: 500
Withdraw: 1500

Sample Output 1:

1000
1500
1000
1000
Write a program in Java 17
import java.util.concurrent.atomic.AtomicLong;

class BankAccount {
private AtomicLong balance;

public BankAccount(long initialBalance) {
balance = new AtomicLong(initialBalance);
}

public void deposit(long amount) {
//Write your code here
}

public boolean withdraw(long amount) {
//Write your code here
}

public long getBalance() {
//Write your code here
}
}
___

Create a free account to access the full topic