io.github.sinri.keel.cache.temporaryvalue.KeelTemporaryValue Maven / Gradle / Ivy
Show all versions of Keel Show documentation
package io.github.sinri.keel.cache.temporaryvalue;
import io.github.sinri.keel.cache.ValueWrapper;
import javax.annotation.Nonnull;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
/**
* @since 3.0.1
*/
public class KeelTemporaryValue {
private final AtomicReference> valueWrapperAtomicReference;
private long defaultLifetimeInSeconds = 10L;
public KeelTemporaryValue() {
this.valueWrapperAtomicReference = new AtomicReference<>();
}
public KeelTemporaryValue setDefaultLifetimeInSeconds(long defaultLifetimeInSeconds) {
this.defaultLifetimeInSeconds = defaultLifetimeInSeconds;
return this;
}
public KeelTemporaryValue
set(P p) {
return set(p, defaultLifetimeInSeconds);
}
public KeelTemporaryValue
set(P p, long lifeInSeconds) {
this.valueWrapperAtomicReference.set(new ValueWrapper<>(p, lifeInSeconds));
return this;
}
public P rawGet() throws ValueInvalidNow {
ValueWrapper
pValueWrapper = this.valueWrapperAtomicReference.get();
if (pValueWrapper == null) {
throw new ValueInvalidNow();
}
if (!pValueWrapper.isAliveNow()) {
throw new ValueInvalidNow();
}
return pValueWrapper.getValue();
}
public P get() {
return getOrElse(null);
}
public P getOrElse(P fallback) {
try {
return rawGet();
} catch (ValueInvalidNow e) {
return fallback;
}
}
public P getOrReload(@Nonnull Supplier
loader) {
ValueWrapper
pValueWrapper = this.valueWrapperAtomicReference.get();
try {
if (pValueWrapper == null) {
throw new ValueInvalidNow();
}
if (!pValueWrapper.isAliveNow()) {
throw new ValueInvalidNow();
}
return pValueWrapper.getValue();
} catch (ValueInvalidNow e) {
var p = loader.get();
if (p != null) {
this.set(p);
}
return p;
}
}
}