Last active
March 7, 2024 00:52
-
-
Save rucko24/b45dbe7519fd4535b7b6a97ea65ba66b to your computer and use it in GitHub Desktop.
BankAccountWithAtomicReference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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