Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up some redundant logic in Expiring cache #134

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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