diff --git a/src/main/java/net/woggioni/jwo/LazyValue.java b/src/main/java/net/woggioni/jwo/LazyValue.java index e92c066..1c3331e 100644 --- a/src/main/java/net/woggioni/jwo/LazyValue.java +++ b/src/main/java/net/woggioni/jwo/LazyValue.java @@ -1,13 +1,22 @@ package net.woggioni.jwo; -import java.util.function.Supplier; import lombok.RequiredArgsConstructor; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Supplier; + @RequiredArgsConstructor public class LazyValue { private final Supplier valueSupplier; + + private final Consumer finalizer; private final MutableTuple2 instance = MutableTuple2.newInstance(null, false); + public LazyValue(Supplier valueSupplier) { + this(valueSupplier, null); + } + public T get() { if(instance.get_2()) return instance.get_1(); synchronized (instance) { @@ -20,4 +29,22 @@ public class LazyValue { } } } + + /** + * Execute the finalized on the wrapped object, if it has been initialized, and then returns it. + * It does nothing if {@link LazyValue#get()} has never been invoked. + * @return the wrapped value if initialized, otherwise an empty {@link Optional} + */ + public Optional close() { + T result = null; + synchronized (instance) { + if(instance.get_2()) { + instance.set_2(false); + result = instance.get_1(); + instance.set_1(null); + } + } + if(result != null) finalizer.accept(result); + return Optional.ofNullable(result); + } } diff --git a/src/main/java/net/woggioni/jwo/Run.java b/src/main/java/net/woggioni/jwo/Run.java new file mode 100644 index 0000000..12a149e --- /dev/null +++ b/src/main/java/net/woggioni/jwo/Run.java @@ -0,0 +1,14 @@ +package net.woggioni.jwo; + +import lombok.SneakyThrows; + +@FunctionalInterface +public interface Run extends Runnable { + @Override + @SneakyThrows + default void run() { + exec(); + } + + boolean exec() throws Throwable; +}