在以下情况下是否需要进行空检查?
我正在阅读 Lombok 库的 lazy getter 示例,但无法弄清楚为什么 null 检查是应用于 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;
}
}
I was reading the lazy getter example of the Lombok library, but could not figure out why the null check is applied to actualValue
, as marked below:
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
expcious()
实现只是一个演示。这个想法是允许计算返回 null 并由 getter 缓存它。为了与未初始化状态区分开来,它缓存AtomicReference
本身,作为计算已完成并返回 null 的指示。这是一种很笨拙的方法,但它可以完成工作。The
expensive()
implementation is just a demo. The idea is to allow the computation to return null and have it cached by the getter. To differentiate from the uninitialized state, it caches theAtomicReference
itself as an indication that the computation was done and returned null. It's a hacky approach, but it gets the job done.