gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:50:27 24 4
gpt4 key购买 nike

在 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 thefirst call to get() and returns that value on subsequent calls toget(). See: memoization

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

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com