【问题标题】:Understanding lazy initialization singleton in dagger2 ScopedProvider by Gregory KickGregory Kick 理解 dagger2 ScopedProvider 中的惰性初始化单例
【发布时间】:2016-12-03 02:44:00
【问题描述】:

我正在阅读Dagger2的源码,在ScopedProvider中有一个静态字段UNINITIALIZED,表示instance字段还没有初始化。我已经阅读并理解了 double-check-lazy-initialization 习语,但为什么需要定义 UNINITIALIZED 字段而不是仅使用 null?是 JVM 的问题吗?

/**
 * A {@link Provider} implementation that memoizes the result of a {@link Factory} instance.
 *
 * @author Gregory Kick
 * @since 2.0
 */
public final class ScopedProvider<T> implements Provider<T> {
    private static final Object UNINITIALIZED = new Object();

    private final Factory<T> factory;
    private volatile Object instance = UNINITIALIZED;

    private ScopedProvider(Factory<T> factory) {
        assert factory != null;
        this.factory = factory;
    }

    @SuppressWarnings("unchecked") // cast only happens when result comes from the factory
    @Override
    public T get() {
        // double-check idiom from EJ2: Item 71
        Object result = instance;
        if (result == UNINITIALIZED) {
            synchronized (this) {
                result = instance;
                if (result == UNINITIALIZED) {
                    instance = result = factory.get();
                }
            }
        }
        return (T) result;
    }

    /** Returns a new scoped provider for the given factory. */
    public static <T> Provider<T> create(Factory<T> factory) {
        if (factory == null) {
            throw new NullPointerException();
        }
        return new ScopedProvider<T>(factory);
    }
}

【问题讨论】:

    标签: java multithreading jvm dagger-2


    【解决方案1】:

    看起来这是一个惰性的 null 安全初始化。想象一下,如果工厂返回 null 并且该代码使用 null 作为标记值,​​而不是 UNINITIALIZED。每次调用 get() 都会进入同步块,因为它不知道 null 实际上是工厂结果,而不仅仅是未初始化状态。

    此代码允许工厂返回 null 并将结果正确存储在 volatile 字段中,以便后续读取不会产生完全同步的开销。

    【讨论】:

      猜你喜欢
      • 2013-05-22
      • 2021-11-21
      • 2018-11-06
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 2013-05-22
      • 1970-01-01
      • 2019-12-15
      相关资源
      最近更新 更多