Java 8是否缓存了对供应商的支持? [英] Does Java 8 have cached support for suppliers?

查看:100
本文介绍了Java 8是否缓存了对供应商的支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

番石榴图书馆拥有它自己的 供应商 ,不扩展Java 8 供应商 。 guava还为供应商提供缓存 - 供应商#memoize

The guava library has it's own Supplier which does not extend Java 8 Supplier. Also guava provides a cache for suppliers - Suppliers#memoize.

是否有类似的东西,但对于Java 8供应商?

Is there something similar, but for Java 8 Suppliers?

推荐答案

最简单的解决方案是

public static <T> Supplier<T> memoize(Supplier<T> original) {
    ConcurrentHashMap<Object, T> store=new ConcurrentHashMap<>();
    return ()->store.computeIfAbsent("dummy", key->original.get());
}

然而,最简单的并不总是效率最高。

However, the simplest is not always the most efficient.

如果你想要一个干净有效的解决方案,诉诸匿名内部类来保持可变状态将会得到回报:

If you want a clean and efficient solution, resorting to an anonymous inner class to hold the mutable state will pay off:

public static <T> Supplier<T> memoize1(Supplier<T> original) {
    return new Supplier<T>() {
        Supplier<T> delegate = this::firstTime;
        boolean initialized;
        public T get() {
            return delegate.get();
        }
        private synchronized T firstTime() {
            if(!initialized) {
                T value=original.get();
                delegate=() -> value;
                initialized=true;
            }
            return delegate.get();
        }
    };
}

这使用代表供应商,它将在第一次操作时进行,然后更换本身与供应商无条件地返回第一次评估的捕获结果。由于它具有 final 字段语义,因此可以无条件地返回它而无需任何其他同步。

This uses a delegate supplier which will do the first time operation and afterwards, replace itself with a supplier that unconditionally returns the captured result of the first evaluation. Since it has final fields semantics, it can be unconditionally returned without any additional synchronization.

在<$ c内$ c> synchronized 方法 firstTime(),仍然需要初始化标志,因为在初始化期间并发访问的情况下,多个线程可以在替换委托之前在方法的条目处等待。因此,这些线程需要检测已经完成初始化。所有后续访问都将读取新的委托供应商并快速获取值。

Inside the synchronized method firstTime(), there is still an initialized flag needed because in case of concurrent access during initialization, multiple threads may wait at the method’s entry before the delegate has been replaced. Hence, these threads need to detect that the initialization has been done already. All subsequent accesses will read the new delegate supplier and get the value quickly.

这篇关于Java 8是否缓存了对供应商的支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆