在以下上下文中是否需要空检查?
Is the null check necessary in the following context?
我正在阅读 Lombok 库的 lazy getter example,但无法弄清楚为什么空检查应用于 actualValue
,如下所示:
public class GetterLazyExample {
private final java.util.concurrent.AtomicReference<java.lang.Object> cached = new java.util.concurrent.AtomicReference<java.lang.Object>();
public double[] getCached() {
java.lang.Object value = this.cached.get();
if (value == null) {
synchronized(this.cached) {
value = this.cached.get();
if (value == null) {
final double[] actualValue = expensive(); // the `actualValue can't be null here, right?
value = actualValue == null ? this.cached : actualValue; // why null check `actualValue`?
this.cached.set(value);
}
}
}
return (double[])(value == this.cached ? null : value);
}
private double[] expensive() {
double[] result = new double[1000000]; // `new` won't return null, if not throwing OutOfMemoryError, right?
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
}
expensive()
实现只是一个演示。这个想法是允许计算 return null 并由 getter 缓存它。为了与未初始化状态区分开来,它缓存 AtomicReference
本身作为计算已完成的指示并且 return 为空。这是一种 hacky 方法,但它完成了工作。
我正在阅读 Lombok 库的 lazy getter example,但无法弄清楚为什么空检查应用于 actualValue
,如下所示:
public class GetterLazyExample {
private final java.util.concurrent.AtomicReference<java.lang.Object> cached = new java.util.concurrent.AtomicReference<java.lang.Object>();
public double[] getCached() {
java.lang.Object value = this.cached.get();
if (value == null) {
synchronized(this.cached) {
value = this.cached.get();
if (value == null) {
final double[] actualValue = expensive(); // the `actualValue can't be null here, right?
value = actualValue == null ? this.cached : actualValue; // why null check `actualValue`?
this.cached.set(value);
}
}
}
return (double[])(value == this.cached ? null : value);
}
private double[] expensive() {
double[] result = new double[1000000]; // `new` won't return null, if not throwing OutOfMemoryError, right?
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
}
expensive()
实现只是一个演示。这个想法是允许计算 return null 并由 getter 缓存它。为了与未初始化状态区分开来,它缓存 AtomicReference
本身作为计算已完成的指示并且 return 为空。这是一种 hacky 方法,但它完成了工作。