Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala lazy values : performance penalty? Threadsafe? [duplicate]

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.

like image 954
Hans-Peter Störr Avatar asked Nov 04 '10 09:11

Hans-Peter Störr


2 Answers

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.

like image 96
Alexey Romanov Avatar answered Oct 05 '22 23:10

Alexey Romanov


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

like image 43
IttayD Avatar answered Oct 06 '22 00:10

IttayD