문제

Possible Duplicate:
What's the (hidden) cost of lazy val? (Scala)

Scala allows the definition of lazy values

lazy val maybeUnusedValue = someCostlyInitialization

where someCostlyInitialization is evaluated only on the first use of maybeUnusedValue. That is, it is evaluated at most once, and if maybeUnusedValue is never used, it is also never evaluated at all.

Is this threadsafe? What are the performance implications of this? If this is to be threadsafe, it has to use some kind of syncronization / use Java volatile in some way. Unfortunately the Scala language specification says nothing about this.

도움이 되었습니까?

해결책

It is made thread-safe using double-checked locking http://code-o-matic.blogspot.com/2009/05/double-checked-locking-idiom-sweet-in.html Obviously this does mean that accessing lazy vals is slower than non-lazy ones.

다른 팁

UPDATE: OOPS, as Vasil pointed out, the question is a copy of another thread, and as it happens, so is this answer.

I took this class:

class Foo {
  lazy val test = "hi"
}

Compiled and decompiled (with jd-gui):

public class Foo
  implements ScalaObject
{
  private String test;
  public volatile int bitmap$0;

  public String test()
  {
    if (
      (this.bitmap$0 & 0x1) == 0);
    synchronized (this)
    {
      if (
        (this.bitmap$0 & 0x1) == 0) {
        this.test = "hi"; this.bitmap$0 |= 1; } return this.test;
    }
  }
}

As you can see it is using the double check paradigm with a volatile variable. So I think it is safe

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top