简体   繁体   English

在java中实现一个懒惰的供应商

[英]implementing a lazy Supplier in java

What is the right paradigm or utility class (can't seem to find a preexisting class) to implement a lazy supplier in Java?在 Java 中实现惰性供应商的正确范例或实用程序类(似乎找不到预先存在的类)是什么?

I want to have something that handles the compute-once/cache-later behavior and allows me to specify the computation behavior independently.我想要一些东西来处理一次计算/稍后缓存行为,并允许我独立指定计算行为。 I know this probably has an error but it has the right semantics:我知道这可能有错误,但它具有正确的语义:

abstract public class LazySupplier<T> implements Supplier<T> 
{
    private volatile T t;
    final private Object lock = new Object();

    final public T get() {
        if (t == null)
        {
            synchronized(lock)
            {
                if (t == null)
                    t = compute();
            }
        }
        return t;
    }
    abstract protected T compute();
}

This is already implemented in Suppliers.memoize method.这已经在Suppliers.memoize方法中实现。

public static <T> Supplier<T> memoize(Supplier<T> delegate)

Returns a supplier which caches the instance retrieved during the first call to get() and returns that value on subsequent calls to get().返回一个供应商,它缓存在第一次调用 get() 期间检索到的实例,并在后续调用 get() 时返回该值。 See: memoization请参阅:记忆

The returned supplier is thread-safe.返回的供应商是线程安全的。 The delegate's get() method will be invoked at most once.委托的 get() 方法最多将被调用一次。 The supplier's serialized form does not contain the cached value, which will be recalculated when get() is called on the reserialized instance.供应商的序列化形式不包含缓存值,当在重新序列化实例上调用 get() 时将重新计算缓存值。

If delegate is an instance created by an earlier call to memoize, it is returned directly.如果 delegate 是之前调用 memoize 创建的实例,则直接返回。

Apache Commons Lang has a LazyInitializer . Apache Commons Lang 有一个LazyInitializer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM