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

标签 java guava lazy-evaluation

在 Java 中实现惰性供应商的正确范例或实用程序类(似乎找不到预先存在的类)是什么?

我想要一些东西来处理一次计算/稍后缓存行为,并允许我独立指定计算行为。我知道这可能有错误,但它具有正确的语义:

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();
}

最佳答案

这已在 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(). 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.

关于java - 在java中实现一个懒惰的供应商,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13663655/

相关文章:

java - 所有 Null、任何 Null 都是可能的 Guava 谓词

ocaml - OCaml 的 Lazy.lazy_from_val 的目的是什么?

java - Java 中本地集合的类型约定

java - Java 语言规范有手机版吗?

java - for 循环的内存占用

Java 获取大输入流的大小导致内存不足

java - 在群集上运行jar时出现NoSuchMethodError

Java,没有同步的延迟初始化字段

c# - C#如何使用正则表达式拆分(A:B = C)*?

java - 单个大型 Web 应用程序还是多个小型 Web 应用程序?