Last active
March 7, 2024 00:27
-
-
Save rucko24/873358fa4feee5913d61f9af47b445fa to your computer and use it in GitHub Desktop.
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.locks.StampedLock; | |
import java.util.function.Supplier; | |
public class BankAccountWithStampedLock { | |
private final StampedLock stampedLock = new StampedLock(); | |
private BankAccount bankAccount; | |
public BankAccountWithStampedLockV2(BankAccount bankAccount) { | |
this.bankAccount = bankAccount; | |
} | |
public <T> T tryOptimisticRead(final Runnable runnable, final Supplier<T> processEntity) { | |
var stamped = this.stampedLock.tryOptimisticRead(); | |
runnable.run(); //execute read | |
if (!this.stampedLock.validate(stamped)) { | |
stamped = this.stampedLock.readLock(); | |
try { | |
runnable.run(); //execute read | |
} finally { | |
this.stampedLock.unlockRead(stamped); | |
} | |
} | |
return processEntity.get(); | |
} | |
public void deposit(double amount) { | |
var stamped = this.stampedLock.writeLock(); | |
try { | |
bankAccount.deposit(amount); | |
} finally { | |
this.stampedLock.unlockWrite(stamped); | |
} | |
} | |
public void withdraw(double amount) { | |
var stamped = this.stampedLock.writeLock(); | |
try { | |
bankAccount.withdraw(amount); | |
} finally { | |
this.stampedLock.unlockWrite(stamped); | |
} | |
} | |
public double getBalance() { | |
return bankAccount.getBalance(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment