我知道在一个类里面使用lazy val使用某种类型的双锁模式。但是在函数定义中呢?它是否使用相同的模式?
例如:
class Sample {
def computation(): Something = {}
def fn(compute: Boolean, default: Something): Something = {
lazy val c = computation()
if (compute) c*c else default
}
}
答案 0 :(得分:10)
是的,它使用相同的模式。请参阅您的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()
{
}
}