added Run interface and small improvements to LazyValue
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
14
src/main/java/net/woggioni/jwo/Run.java
Normal file
14
src/main/java/net/woggioni/jwo/Run.java
Normal 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;
|
||||
}
|
Reference in New Issue
Block a user