• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Scala关键字lazy的见解

武飞扬头像
kiritobryant
帮助1

Scala中使用关键字lazy来定义惰性变量,实现延迟加载(懒加载)。
惰性变量只能是不可变变量,并且只有在调用惰性变量时,才会去实例化这个变量。

在Java中,要实现延迟加载(懒加载),需要自己手动实现。一般的做法是这样的:

  1.  
     
  2.  
    public class LazyDemo {
  3.  
     
  4.  
    private String property;
  5.  
     
  6.  
    public String getProperty() {
  7.  
    if (property == null) {//如果没有初始化过,那么进行初始化
  8.  
    property = initProperty();
  9.  
    }
  10.  
    return property;
  11.  
    }
  12.  
     
  13.  
    private String initProperty() {
  14.  
    return "property";
  15.  
    }
  16.  
    }

比如常用的单例模式懒汉式实现时就使用了上面类似的思路实现。

而在Scala中对延迟加载这一特性提供了语法级别的支持:

lazy val property = initProperty()

使用lazy关键字修饰变量后,只有在使用该变量时,才会调用其实例化方法。也就是说在定义property=initProperty()时并不会调用initProperty()方法,只有在后面的代码中使用变量property时才会调用initProperty()方法。

如果不使用lazy关键字对变量修饰,那么变量property是立即实例化的:

  1.  
     
  2.  
    object LazyOps {
  3.  
     
  4.  
    def init(): String = {
  5.  
    println("call init()")
  6.  
    return ""
  7.  
    }
  8.  
     
  9.  
    def main(args: Array[String]) {
  10.  
    val property = init();//没有使用lazy修饰
  11.  
    println("after init()")
  12.  
    println(property)
  13.  
    }
  14.  
     
  15.  
    }

上面的property没有使用lazy关键字进行修饰,所以property是立即实例化的,如果观察程序的输出:

  1.  
    call init()
  2.  
    after init()

可以发现,property声明时,立即进行实例化,调用了`init()``实例化方法

而如果使用lazy关键字进行修饰:

  1.  
    object LazyOps {
  2.  
     
  3.  
    def init(): String = {
  4.  
    println("call init()")
  5.  
    return ""
  6.  
    }
  7.  
     
  8.  
    def main(args: Array[String]) {
  9.  
    lazy val property = init();//使用lazy修饰
  10.  
    println("after init()")
  11.  
    println(property)
  12.  
    println(property)
  13.  
    }
  14.  
     
  15.  
    }

观察输出:

  1.  
    after init()
  2.  
    call init()

在声明property时,并没有立即调用实例化方法intit(),而是在使用property时,才会调用实例化方法,并且无论缩少次调用,实例化方法只会执行一次。

与Java相比起来,实现懒加载确实比较方便了。那么Scala是如何实现这个语法糖的呢?反编译看下Scala生成的class:

  1.  
    private final String property$lzycompute$1(ObjectRef property$lzy$1, VolatileByteRef bitmap$0$1)
  2.  
    {
  3.  
    synchronized (this)//加锁
  4.  
    {
  5.  
    if ((byte)(bitmap$0$1.elem & 0x1) == 0)//如果属性不为null
  6.  
    {//那么进行初始化
  7.  
    property$lzy$1.elem = init();bitmap$0$1.elem = ((byte)(bitmap$0$1.elem | 0x1));
  8.  
    }
  9.  
    return (String)property$lzy$1.elem;
  10.  
    }
  11.  
    }

原理探究
scala也是编译成字节码跑在jvm上的,而jvm的字节码指令并没有提供对lazy这种语义的支持,所以由此可以推断,lazy只是一个语法糖,scala编译器在编译时期对其做一些包装转换,但究竟是如何转换的呢,可以写一段代码编译然后反编译看一下。

编写一段scala代码,有两个变量,一个使用lazy修饰,一个不使用lazy修饰:

  1.  
    package cc11001100.scala.lazyStudy
  2.  
     
  3.  
    class LazyInitDemoForDecompilation {
  4.  
    lazy val foo = "foo"
  5.  
    val bar = "bar"
  6.  
    }
  7.  
     
  8.  
    object LazyInitDemoForDecompilation {
  9.  
     
  10.  
    def main(args: Array[String]): Unit = {
  11.  
    val o = new LazyInitDemoForDecompilation()
  12.  
    println(o.foo)
  13.  
    println(o.bar)
  14.  
    }
  15.  
     
  16.  
    }

然后编译为字节码文件,再使用jd-gui等工具将其反编译:

  1.  
    package cc11001100.scala.lazyStudy;
  2.  
     
  3.  
    import scala.reflect.ScalaSignature;
  4.  
     
  5.  
    @ScalaSignature(bytes="\006\001}2A!\003\006\001#!)q\003\001C\0011!A1\004\001EC\002\023\005A\004C\004&\001\t\007I\021\001\017\t\r\031\002\001\025!\003\036\017\0259#\002#\001)\r\025I!\002#\001*\021\0259b\001\"\001 \021\025Yc\001\"\001-\005qa\025M_=J]&$H)Z7p\r>\024H)Z2p[BLG.\031;j_:T!a\003\007\002\0231\f'0_*uk\022L(BA\007\017\003\025\0318-\0317b\025\005y\021AC2dcE\002\004'M\0311a\r\0011C\001\001\023!\t\031R#D\001\025\025\005i\021B\001\f\025\005\031\te.\037*fM\0061A(\0338jiz\"\022!\007\t\0035\001i\021AC\001\004M>|W#A\017\021\005y\031S\"A\020\013\005\001\n\023\001\0027b]\036T\021AI\001\005U\0064\030-\003\002%?\t11\013\036:j]\036\f1AY1s\003\021\021\027M\035\021\00291\013'0_%oSR$U-\\8G_J$UmY8na&d\027\r^5p]B\021!DB\n\003\rI!\022\001K\001\005[\006Lg\016\006\002.aA\0211CL\005\003_Q\021A!\0268ji\")\021\007\003a\001e\005!\021M]4t!\r\0312'N\005\003iQ\021Q!\021:sCf\004\"AN\037\017\005]Z\004C\001\035\025\033\005I$B\001\036\021\003\031a$o\\8u}%\021A\bF\001\007!J,G-\0324\n\005\021r$B\001\037\025\001")
  6.  
    public class LazyInitDemoForDecompilation
  7.  
    {
  8.  
    private String foo;
  9.  
     
  10.  
    private String foo$lzycompute()
  11.  
    {
  12.  
    // 因为在调用此方法之前已经判断过一次标志位的值了,
  13.  
    // 所以可以看做是一种被拆散了的DCL
  14.  
    synchronized (this)
  15.  
    {
  16.  
    if (!this.bitmap$0)
  17.  
    {
  18.  
    this.foo = "foo";
  19.  
    this.bitmap$0 = true;
  20.  
    }
  21.  
    }
  22.  
    return this.foo;
  23.  
    }
  24.  
     
  25.  
    public String foo()
  26.  
    {
  27.  
    // 每次获取foo的值的时候,先判断是否已经初始化过了,
  28.  
    // 如果还没有初始化就将其初始化,否则直接将已经计算出的值返回
  29.  
    return !this.bitmap$0 ? foo$lzycompute() : this.foo;
  30.  
    }
  31.  
     
  32.  
    public String bar()
  33.  
    {
  34.  
    return this.bar;
  35.  
    }
  36.  
     
  37.  
    // bar变量直接为其赋值的
  38.  
    private final String bar = "bar";
  39.  
    // 这个变量是一个标志位,用来记录foo变量是否已经被初始化过了
  40.  
    private volatile boolean bitmap$0;
  41.  
     
  42.  
    public static void main(String[] paramArrayOfString)
  43.  
    {
  44.  
    LazyInitDemoForDecompilation..MODULE$.main(paramArrayOfString);
  45.  
    }
  46.  
    }

在object中执行:

  1.  
    package cc11001100.scala.lazyStudy;
  2.  
     
  3.  
    import scala.Predef.;
  4.  
     
  5.  
    public final class LazyInitDemoForDecompilation$
  6.  
    {
  7.  
    public static MODULE$;
  8.  
     
  9.  
    static
  10.  
    {
  11.  
    new ();
  12.  
    }
  13.  
     
  14.  
    public void main(String[] args)
  15.  
    {
  16.  
    LazyInitDemoForDecompilation o = new LazyInitDemoForDecompilation();
  17.  
    // 会将对变量的访问替换成调用访问器,
  18.  
    // 这样的话编译器就可以很鸡贼的在访问器方法中插入各种处理以提供N多的语法糖,挺机智的
  19.  
    Predef..MODULE$.println(o.foo());
  20.  
    Predef..MODULE$.println(o.bar());
  21.  
    }
  22.  
     
  23.  
    private LazyInitDemoForDecompilation$()
  24.  
    {
  25.  
    MODULE$ = this;
  26.  
    }
  27.  
    }

综上源码,得出结论,scala的lazy关键字就是编译器在编译期将变量的初始化过程替换为Double Check Lock,类似于Java中的懒汉式单例模式初始化。

Scala同样使用了Java中常用的懒加载的方式自动帮助我们实现了延迟加载,并且还加锁避免多个线程同时调用初始化方法可能导致的不一致问题。

对于这样一个表达式: lazy val t:T = expr 无论expr是什么东西,字面量也好,方法调用也好。Scala的编译器都会把这个expr包在一个方法中,并且生成一个flag来决定只在t第一次被访问时才调用该方法。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgkhgaj
系列文章
更多 icon
同类精品
更多 icon
继续加载