@Getter(lazy=true)

@Getter(lazy=true)

懒惰是一种美德!
@Getter(lazy=true) 在Lombok v0.10中引入。

Overview

你可以让lombok生成一个getter,它会在第一次调用这个getter时计算一次值,然后从那里开始缓存它。如果计算该值需要大量CPU,或者该值占用大量内存,这可能很有用。要使用此功能,请创建一个private final变量,使用运行成本高的表达式对其进行初始化,并使用@Getter(lazy=true)。该字段将从其余代码中隐藏,并且在首次调用getter时,表达式将被评估不超过一次。没有魔术标记值(即使你的计算结果昂贵null,结果是缓存的),而且昂贵的计算不需要是线程安全的,因为lombok负责锁定。

如果初始化表达式很复杂或包含泛型,我们建议将代码移动到私有(如果可能的静态)方法,并调用它。

With Lombok

import lombok.Getter;

public class GetterLazyExample {
  @Getter(lazy=true) private final double[] cached = expensive();
  
  private double[] expensive() {
    double[] result = new double[1000000];
    for (int i = 0; i < result.length; i++) {
      result[i] = Math.asin(i);
    }
    return result;
  }
}

Vanilla Java

public class GetterLazyExample {
  private final java.util.concurrent.AtomicReference cached = new java.util.concurrent.AtomicReference();
  
  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();
          value = actualValue == null ? this.cached : actualValue;
          this.cached.set(value);
        }
      }
    }
    return (double[])(value == this.cached ? null : value);
  }
  
  private double[] expensive() {
    double[] result = new double[1000000];
    for (int i = 0; i < result.length; i++) {
      result[i] = Math.asin(i);
    }
    return result;
  }
}

Supported configuration keys:

lombok.getter.lazy.flagUsage = [warning | error] (default: not set)

Small print

你永远不应该直接引用这个字段,总是使用lombok生成的getter,因为字段的类型会被破坏成一个AtomicReference。不要试图直接访问它AtomicReference; 如果它指向自己,那么该值已经计算出来了null。如果参考指向null,则表示该值尚未计算。在将来的版本中,此行为可能会更改 因此,始终使用生成的getter访问您的字段!

其他Lombok注释,@ToString即使你使用也总是调用getter doNotUseGetters=true。

你可能感兴趣的:(@Getter(lazy=true))