Created
May 25, 2021 17:37
-
-
Save mtbarr/9168b73291cea3b4f2d1dcc447a762fc to your computer and use it in GitHub Desktop.
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
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