我知道在使用惰性val的类中使用某种类型的双锁模式。但是在函数定义内部呢?是否使用相同的模式?

例如:

class Sample {
  def computation(): Something = {}

  def fn(compute: Boolean, default: Something): Something = {
    lazy val c = computation()

    if (compute) c*c else default
  }
}

最佳答案

是的,它使用相同的模式。查看您的Scala代码:

class Sample {
  def computation(): Int = 100

  def fn(compute: Boolean, default: Int): Int = {
    lazy val c = computation()

    if (compute) c*c else default
  }
}


用scalac编译并用jad反编译:

public class Sample implements ScalaObject
{

    public int computation()
    {
        return 100;
    }

    public int fn(boolean compute, int default)
    {
        VolatileIntRef bitmap$0$1 = new VolatileIntRef(0);
        IntRef c$lzy$1 = new IntRef(0);
        return compute ? c$1(c$lzy$1, bitmap$0$1) * c$1(c$lzy$1, bitmap$0$1) : default;
    }

    private final int c$1(IntRef intref, VolatileIntRef volatileintref)
    {
        if((volatileintref.elem & 1) == 0)
            synchronized(this)
            {
                if((volatileintref.elem & 1) == 0)
                {
                    intref.elem = computation();
                    volatileintref.elem = volatileintref.elem | 1;
                }
                BoxedUnit _tmp = BoxedUnit.UNIT;
            }
        return intref.elem;
    }

    public Sample()
    {
    }
}

08-25 02:13