Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions helper/src/main/java/me/lucko/helper/cache/Expiring.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ public static <T> Expiring<T> suppliedBy(Supplier<T> supplier, long duration, Ti

private volatile T value;

// when to expire. 0 means "not yet initialized".
private volatile long expirationNanos;
private volatile long expirationNanos = System.nanoTime();

private Expiring(Supplier<T> supplier, long duration, TimeUnit unit) {
this.supplier = supplier;
Expand All @@ -67,18 +66,15 @@ public T get() {
long nanos = this.expirationNanos;
long now = System.nanoTime();

if (nanos == 0 || now - nanos >= 0) {
if (now - nanos >= 0) {
synchronized (this) {
if (nanos == this.expirationNanos) { // recheck for lost race
// compute the value using the delegate
T t = this.supplier.get();
this.value = t;

// reset expiration timer
nanos = now + this.durationNanos;
// In the very unlikely event that nanos is 0, set it to 1;
// no one will notice 1 ns of tardiness.
this.expirationNanos = (nanos == 0) ? 1 : nanos;
this.expirationNanos = now + this.durationNanos;
return t;
}
}
Expand Down