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

org.comroid.api.Provider Maven / Gradle / Ivy

The newest version!
package org.comroid.api;

import org.comroid.annotations.Blocking;
import org.jetbrains.annotations.ApiStatus.Internal;
import org.jetbrains.annotations.Contract;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

@FunctionalInterface
public interface Provider extends Supplier> {
    default boolean isInstant() {
        return this instanceof Now;
    }

    static  Provider of(CompletableFuture future) {
        return Polyfill.constantSupplier(future)::get;
    }

    static  Provider.Now of(Supplier supplier) {
        return supplier::get;
    }

    static  Provider.Now constant(T value) {
        return Objects.isNull(value) ? empty() : (Now) Support.Constant.cache.computeIfAbsent(value, Support.Constant::new);
    }

    static  Provider.Now empty() {
        return (Now) Support.EMPTY;
    }

    static  Provider completingOnce(CompletableFuture from) {
        return new Support.Once<>(from);
    }

    @Blocking
    default T now() {
        return get().join();
    }

    CompletableFuture get();

    @FunctionalInterface
    interface Now extends Provider {
        @Override
        default boolean isInstant() {
            return true;
        }

        @Override
        T now();

        @Override
        @Contract("-> new")
        default CompletableFuture get() {
            return CompletableFuture.completedFuture(now());
        }
    }

    @Internal
    final class Support {
        private static final Provider EMPTY = constant(null);

        private static final class Constant implements Provider.Now {
            private static final Map> cache = new ConcurrentHashMap<>();
            private final T value;

            private Constant(T value) {
                this.value = value;
            }

            @Override
            public T now() {
                return value;
            }
        }

        private static final class Once implements Provider {
            private final CompletableFuture future;

            public Once(CompletableFuture from) {
                this.future = from;
            }

            @Override
            public CompletableFuture get() {
                return future;
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy