implementing a lazy Supplier in java

送分小仙女□ 提交于 2020-12-29 09:04:08

问题


What is the right paradigm or utility class (can't seem to find a preexisting class) to implement a lazy supplier in 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();
}

回答1:


This is already implemented in Suppliers.memoize method.

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(). See: memoization

The returned supplier is thread-safe. The delegate's get() method will be invoked at most once. The supplier's serialized form does not contain the cached value, which will be recalculated when get() is called on the reserialized instance.

If delegate is an instance created by an earlier call to memoize, it is returned directly.




回答2:


Apache Commons Lang has a LazyInitializer.



来源:https://stackoverflow.com/questions/13663655/implementing-a-lazy-supplier-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!