2022-07-20 13:18:57 +02:00
|
|
|
package fr.pandacube.lib.util;
|
2021-08-08 12:56:36 +02:00
|
|
|
|
|
|
|
import java.util.Objects;
|
|
|
|
import java.util.function.Supplier;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Represents a lazy loaded value.
|
|
|
|
*
|
|
|
|
* The value will be computed using the Supplier provided in the
|
|
|
|
* constructor, only the first time the {@link #get()} method is
|
|
|
|
* called.
|
|
|
|
*
|
|
|
|
* @param <T> the type of the enclosed value.
|
|
|
|
*/
|
|
|
|
public class Lazy<T> implements Supplier<T> {
|
|
|
|
|
|
|
|
private T cachedValue;
|
|
|
|
private final Supplier<T> supplier;
|
|
|
|
private boolean cached = false;
|
2022-07-28 01:13:35 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a lazy value loader that will call the provided supplier to get the value.
|
|
|
|
* @param s the supplier from which the value is fetched.
|
|
|
|
*/
|
2021-08-08 12:56:36 +02:00
|
|
|
public Lazy(Supplier<T> s) {
|
|
|
|
supplier = Objects.requireNonNull(s);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the wrapped value, from cache or from the provider if it is not yet cached.
|
|
|
|
*
|
2022-07-28 01:13:35 +02:00
|
|
|
* If the provider throws an exception, it will be redirected to the caller as is, and no value will be cached
|
|
|
|
* (the next call to this method will execute the supplier again).
|
2021-08-08 12:56:36 +02:00
|
|
|
*/
|
|
|
|
@Override
|
|
|
|
public synchronized T get() {
|
2022-07-28 01:13:35 +02:00
|
|
|
if (!cached)
|
2021-08-08 12:56:36 +02:00
|
|
|
set(supplier.get());
|
|
|
|
return cachedValue;
|
|
|
|
}
|
2022-07-28 01:13:35 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Reset the cached value. The next call to {@link #get()} will get the value from the provider.
|
|
|
|
*/
|
2021-08-08 12:56:36 +02:00
|
|
|
public synchronized void reset() {
|
|
|
|
cached = false;
|
|
|
|
cachedValue = null;
|
|
|
|
}
|
2022-07-28 01:13:35 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Manually set the value to the provided one.
|
|
|
|
* @param value the value to put in the cache.
|
|
|
|
*/
|
2021-08-08 12:56:36 +02:00
|
|
|
public synchronized void set(T value) {
|
|
|
|
cachedValue = value;
|
|
|
|
cached = true;
|
|
|
|
}
|
|
|
|
|
2023-08-27 01:48:09 +02:00
|
|
|
/**
|
|
|
|
* Tells if the value is currently set or not.
|
|
|
|
* @return true if the value has been set by calling the method {@link #get()} or {@link #set(Object)} but not yet
|
|
|
|
* reset by {@link #reset()}, or false otherwise.
|
|
|
|
*/
|
|
|
|
public synchronized boolean isSet() {
|
|
|
|
return cached;
|
|
|
|
}
|
|
|
|
|
2021-08-08 12:56:36 +02:00
|
|
|
}
|