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

shz.cache.SingleCache Maven / Gradle / Ivy

There is a newer version: 2.0
Show newest version
package shz.cache;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.Objects;
import java.util.function.Supplier;

public final class SingleCache extends LocalCache {
    private final Supplier> supplier;
    private Reference ref;

    public SingleCache(RefType refType, Supplier supplier, ReferenceQueue queue) {
        super(refType, queue);
        this.supplier = () -> getReference(supplier.get());
    }

    public SingleCache(RefType refType, Supplier supplier) {
        this(refType, supplier, null);
    }

    public SingleCache(Supplier supplier) {
        this(RefType.SOFT, supplier, null);
    }

    public E get() {
        if (ref == null || ref.isEnqueued()) ref = supplier.get();
        return ref.get();
    }

    public E getNonNull() {
        E value;
        Objects.requireNonNull(value = get());
        return value;
    }

    @Override
    public void clear() {
        if (ref == null) return;
        ref.clear();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy