personthecat.catlib.data.ResettableLazy Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of catlib-quilt Show documentation
Show all versions of catlib-quilt Show documentation
Utilities for serialization, commands, noise generation, IO, and some new data types.
The newest version!
package personthecat.catlib.data;
import org.jetbrains.annotations.NotNull;
import javax.annotation.concurrent.ThreadSafe;
import java.util.function.Supplier;
/**
* Variant of {@link Lazy} which is allowed to be reset.
*
* In addition to being reloadable, this wrapper is threadsafe and provides a guaranteed
* method for retrieving up-to-date values: {@link #getUpdated()}.
*
* @param The type of value being consumed by the wrapper.
*/
@ThreadSafe
@SuppressWarnings({"unused", "UnusedReturnValue"})
public class ResettableLazy extends Lazy {
/**
* The primary constructor with instructions for producing the value.
*
* @param supplier A function used for generating the value, when ready.
*/
public ResettableLazy(@NotNull Supplier supplier) {
super(supplier);
}
/**
* To be used in the event that a value already exists.
*
* @param value The actual value being wrapped.
*/
public ResettableLazy(@NotNull T value) {
super(value);
}
/**
* Factory variant of {@link #ResettableLazy(Supplier)}.
*
* @param The type of value being wrapped.
* @param supplier A supplier providing this value, when the time comes.
* @return The value, to be calculated on first use.s
*/
public static ResettableLazy of(@NotNull final Supplier supplier) {
return new ResettableLazy<>(supplier);
}
/**
* Factory variant of {@link #ResettableLazy(Object)}.
*
* @param The type of value being wrapped.
* @param value The actual value being wrapped.
* @return The value, consumed by the wrapper.
*/
public static ResettableLazy of(@NotNull final T value) {
return new ResettableLazy<>(value);
}
/**
* Converts this wrapper into a resettable or non-resettable value.
*
* @param resettable Whether the wrapper should be resettable.
* @return Either this
or a regular {@link Lazy}.
*/
public Lazy asResettable(final boolean resettable) {
if (resettable) {
return this;
}
return this.set ? new Lazy<>(this.value) : new Lazy<>(this.supplier);
}
/**
* Marks this object as being uninitialized. It will be loaded again on next use.
*
* @return this
, for method chaining.
*/
public synchronized ResettableLazy reset() {
this.set = false;
this.value = null;
return this;
}
/**
* Returns whether the underlying data can be reloaded.
*
* @return true
, always.
*/
@Override
public boolean isResettable() {
return true;
}
}