Skip to content

Instantly share code, notes, and snippets.

@rucko24
Last active March 7, 2024 00:52
Show Gist options
  • Save rucko24/b45dbe7519fd4535b7b6a97ea65ba66b to your computer and use it in GitHub Desktop.
Save rucko24/b45dbe7519fd4535b7b6a97ea65ba66b to your computer and use it in GitHub Desktop.
BankAccountWithAtomicReference
package org.example.bankaccount;
import java.util.concurrent.atomic.AtomicReference;
public class BankAccountWithAtomicReference {
private AtomicReference<BankAccount> atomicBalance = new AtomicReference<>(new BankAccount());
public void deposit(double amount) {
BankAccount oldBalance;
BankAccount newBalance;
do {
oldBalance = atomicBalance.get();
var bank = new BankAccount();
bank.deposit(oldBalance.getBalance() + amount);
newBalance = bank;
} while (!this.atomicBalance.compareAndSet(oldBalance, newBalance));
}
public void withdraw(double amount) {
BankAccount oldBalance;
BankAccount newBalance;
do {
oldBalance = atomicBalance.get();
var bank = new BankAccount();
bank.deposit(oldBalance.getBalance() - amount);
newBalance = bank;
} while (!this.atomicBalance.compareAndSet(oldBalance, newBalance));
}
public double getBalance() {
return this.atomicBalance.get().getBalance();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment