Skip to content

Instantly share code, notes, and snippets.

@vladimir-bukhtoyarov
Last active April 21, 2022 07:09
Show Gist options
  • Save vladimir-bukhtoyarov/269d98d64ad64128336894f8b1c1e956 to your computer and use it in GitHub Desktop.
Save vladimir-bukhtoyarov/269d98d64ad64128336894f8b1c1e956 to your computer and use it in GitHub Desktop.
Example of StamedLock usage
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