【发布时间】: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