added Run interface and small improvements to LazyValue

This commit is contained in:
2022-10-04 18:28:34 +08:00
parent 1a17f5ce22
commit 34f0990334
2 changed files with 42 additions and 1 deletions

View File

@@ -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<T> {
private final Supplier<T> valueSupplier;
private final Consumer<T> finalizer;
private final MutableTuple2<T, Boolean> instance = MutableTuple2.newInstance(null, false);
public LazyValue(Supplier<T> valueSupplier) {
this(valueSupplier, null);
}
public T get() {
if(instance.get_2()) return instance.get_1();
synchronized (instance) {
@@ -20,4 +29,22 @@ public class LazyValue<T> {
}
}
}
/**
* 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<T> 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);
}
}

View File

@@ -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;
}