sirius.kernel.cache.InlineCache Maven / Gradle / Ivy
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.kernel.cache;
import javax.annotation.Nullable;
import java.util.function.Supplier;
/**
* Caches a single value to prevent frequent re-computation.
*
* Caches a computed value for a certain amount of time. Re-computes the value once the value is expired and the
* cache is used again.
*
* A real lookup cache, with a Map like behaviour can be found here: {@link Cache}.
*
* Use {@link CacheManager#createInlineCache(java.time.Duration, java.util.function.Supplier)}
* to create a new inline cache.
*
* @param the type of values being cached
*/
public class InlineCache {
private E buffer;
private long lastComputation;
private long timeout;
private Supplier computer;
/**
* Creates a new inline cache based on the given parameters.
*
* @param computer the function used to compute a value if it is not present in the cache
* @param timeout the time to live (ttl) for the value in milliseconds
*/
protected InlineCache(@Nullable Supplier computer, long timeout) {
this.computer = computer;
this.timeout = timeout;
}
/**
* Either returns a cached value or computes a new one, if no valid value is in the cache.
*
* @return a cached or computed value, generated by the internal ValueProvider
*/
@Nullable
public E get() {
if (System.currentTimeMillis() - lastComputation > timeout) {
buffer = computer.get();
lastComputation = System.currentTimeMillis();
}
return buffer;
}
/**
* Forces the cache to reset and re-compute its internal value on the next access
*/
public void flush() {
lastComputation = 0;
}
}