Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top