com.slimgears.util.stream.Lazy Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of stream-utils Show documentation
Show all versions of stream-utils Show documentation
General purpose utils / module: stream-utils
package com.slimgears.util.stream;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import static com.slimgears.util.stream.Optionals.ofType;
public class Lazy implements Supplier, AutoCloseable {
private final Callable supplier;
private final Object lock = new Object();
private T instance;
private Lazy(Callable supplier) {
this.supplier = supplier;
}
public void ifExists(Consumer consumer) {
synchronized (lock) {
Optional.ofNullable(instance)
.ifPresent(consumer);
}
}
public Lazy map(Function mapper) {
return Lazy.of(() -> mapper.apply(get()));
}
@Override
public T get() {
return Optional
.ofNullable(instance)
.orElseGet(Synchornized
.withLock(lock)
.ofUnsafe(() -> Optional
.ofNullable(instance)
.orElseGet(Safe.ofSupplier(() -> instance = supplier.call()))));
}
public void close() {
Synchornized
.withLock(lock)
.of(() -> Optional
.ofNullable(instance)
.flatMap(ofType(AutoCloseable.class))
.ifPresent(Safe.ofConsumer(AutoCloseable::close)));
}
public static Lazy fromCallable(Callable callable) {
return new Lazy<>(callable);
}
public static Lazy of(Supplier supplier) {
return fromCallable(supplier::get);
}
}