美文网首页Java
lombok @Getter(lazy=true)

lombok @Getter(lazy=true)

作者: 愤怒的老照 | 来源:发表于2020-04-27 10:31 被阅读0次

@Getter(lazy=true)

  • 该标注用于生成一个 lazy 版的 getter,它会在第一次调用这个 getter 时计算一次值,然后从那里开始缓存它。如果计算该值需要大量 CPU,或者该值占用大量内存,这可能很有用。

注意:Lombok 会自动去管理线程安全的问题,所以不会存在重复赋值的问题。

  • 要使用此功能,需要创建一个 private final 变量,并且使用运行成本高的表达式对其进行初始化,同时使用 @Getter(lazy=true) 注解进行标注。

使用注解:

// 使用注解
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;
    }
}

不使用注解

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();
                    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;
    }
}

相关文章

  • @Getter(lazy=true)

    @Getter(lazy=true) 懒惰是一种美德!@Getter(lazy=true) 在Lombok v0....

  • lombok @Getter(lazy=true)

    @Getter(lazy=true) 该标注用于生成一个 lazy 版的 getter,它会在第一次调用这个 ge...

  • 框架注解

    lombok Data -- getter和setter方法 Getter -- getter方法 Setter ...

  • 关于注解

    常见注解 lombok @Data -- getter和setter方法@Getter -- getter方法@S...

  • 常见注解

    常见注解 lombok @Data -- getter和setter方法@Getter -- getter方法@S...

  • 常见的注解

    常见注解 lombok @Data -- getter和setter方法@Getter -- getter方法@S...

  • 统一接口返回类

    import lombok.Getter;import lombok.Setter;import org.apac...

  • SpringBoot学习笔记(七):SpringBoot中lom

    lombok概述 lombok简介Lombok想要解决了的是在我们实体Bean中大量的Getter/Setter方...

  • SpringBoot中lombok使用

    lombok概述 lombok简介Lombok想要解决了的是在我们实体Bean中大量的Getter/Setter方...

  • Lombok常用注解

    Lombok常用注解 加入 maven 依赖 1. @Getter/@Setter 自动产生 getter/set...

网友评论

    本文标题:lombok @Getter(lazy=true)

    本文链接:https://www.haomeiwen.com/subject/bzzewhtx.html