Skip to content

Instantly share code, notes, and snippets.

@mtbarr
Created May 25, 2021 17:37
Show Gist options
  • Save mtbarr/9168b73291cea3b4f2d1dcc447a762fc to your computer and use it in GitHub Desktop.
Save mtbarr/9168b73291cea3b4f2d1dcc447a762fc to your computer and use it in GitHub Desktop.
package io.github.sasuked.legionguilds.utils.cache;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
public class TemporaryValue<T> {
private final Supplier<T> supplier;
private T currentValue;
private final long timeToExpire;
private final TimeUnit unit;
long expirationTime;
public TemporaryValue(Supplier<T> supplier, long timeToExpire, TimeUnit unit) {
this.supplier = supplier;
this.timeToExpire = timeToExpire;
this.unit = unit;
this.expirationTime = System.currentTimeMillis() + (unit.toSeconds(timeToExpire) * 1000);
}
public T getCurrentValue() {
if (currentValue == null || isExpired()) {
currentValue = supplier.get();
expirationTime = System.currentTimeMillis() + (unit.toSeconds(timeToExpire) * 1000);
}
return currentValue;
}
public boolean isExpired() {
return System.currentTimeMillis() >= expirationTime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment