Question lazy implements

Hi guys. Here is an example about lazy

final class LazyCell {
  lazy val value = 12
}

then i decompile class, find this

public final class LazyCell {
   private int value;
   private volatile boolean bitmap$0;

   private int value$lzycompute() {
      synchronized(this){}    //❓ why do this? and i think it should enclose try-catch

      try {
         if (!this.bitmap$0) {
            this.value = 12;
            this.bitmap$0 = true;
         }
      } catch (Throwable var3) {
         throw var3;
      }

      return this.value;
   }

   public int value() {
      return !this.bitmap$0 ? this.value$lzycompute() : this.value;
   }
}

Can some scala guru please explain why synchronized(this){} not synchronized(this){ try -catch }?

scala version is 2.13.6

I would recommend

javap -private -verbose LazyCell.class

Also, I don’t follow closely, but they periodically tweak lazy vals and there is another effort for Scala 3, if the topic is of interest.

thanks :+1:. i think that it maybe intellij’s issue .


private int value$lzycompute();
    descriptor: ()I
    flags: ACC_PRIVATE
    Code:
      stack=2, locals=2, args_size=1
         0: aload_0
         1: dup
         2: astore_1
         3: monitorenter        // ❗️ do something after monitorenter, its different with intellij decompile
         4: aload_0
         5: getfield      #16                 // Field bitmap$0:Z
         8: ifne          22
        11: aload_0
        12: bipush        12
        14: putfield      #18                 // Field value:I
        17: aload_0
        18: iconst_1
        19: putfield      #16                 // Field bitmap$0:Z
        22: aload_1
        23: monitorexit
        24: goto          30
        27: aload_1
        28: monitorexit
        29: athrow
        30: aload_0
        31: getfield      #18                 // Field value:I
        34: ireturn
1 Like