在 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/