Last active
April 21, 2022 07:09
-
-
Save vladimir-bukhtoyarov/269d98d64ad64128336894f8b1c1e956 to your computer and use it in GitHub Desktop.
Example of StamedLock usage
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
import java.time.Duration; | |
import java.util.concurrent.locks.StampedLock; | |
import java.util.function.Supplier; | |
public class CachingSupplier<T> implements Supplier<T> { | |
private final Supplier<T> targetSupplier; | |
private final long cachingDurationNanos; | |
private final StampedLock stampedLock = new StampedLock(); | |
private T cachedValue; | |
private long lastSnapshotNanoTime; | |
private boolean initialized; | |
public CachingSupplier(Duration cachingDuration, Supplier<T> targetSupplier) { | |
this.targetSupplier = targetSupplier; | |
this.cachingDurationNanos = cachingDuration.toNanos(); | |
} | |
@Override | |
final public T get() { | |
long nanoTime = System.nanoTime(); | |
long stamp = stampedLock.tryOptimisticRead(); | |
long lastSnapshotNanoTime = this.lastSnapshotNanoTime; | |
T cachedValue = this.cachedValue; | |
boolean initialized = this.initialized; | |
if (stampedLock.validate(stamp)) { | |
if (initialized && nanoTime - lastSnapshotNanoTime <= cachingDurationNanos) { | |
// основной выигрышь сдесь, мы прошли по всем веткам не выполнив не одной записи | |
return cachedValue; | |
} | |
} | |
stamp = stampedLock.writeLock(); | |
try { | |
nanoTime = System.nanoTime(); | |
if (this.initialized && nanoTime - this.lastSnapshotNanoTime <= cachingDurationNanos) { | |
return this.cachedValue; | |
} | |
this.cachedValue = targetSupplier.get(); | |
this.initialized = true; | |
this.lastSnapshotNanoTime = nanoTime; | |
return this.cachedValue; | |
} finally { | |
stampedLock.unlockWrite(stamp); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment