All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.slimgears.util.stream.Lazy Maven / Gradle / Ivy

There is a newer version: 0.7.58
Show newest version
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);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy