lazy val synchronized

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

lazy val synchronized

Steve Yen
Hi, I'd bet that the following line of code would break in a
multithreaded app...

  lazy val foo =  ... some init code that must run exactly once ...

So, do I just throw in a synchronized keyword to make it right (2)?

  lazy val foo = synchronized { ... some init code that must run
exactly once ... }

Or, perhaps, I need to instead write...

  private lazy val foo_i = ... some init code that must run exactly once ...
  def foo = synchronized { foo_i }

In short, in (2), does the "lazy val" magic part of the code run
outside the "synchronized"?

Thanks,
Steve
Reply | Threaded
Open this post in threaded view
|

Re: lazy val synchronized

The_Danimal
Test:
class Test {
  lazy val foo = "foo"
}

Javap says:
public class Test extends java.lang.Object implements scala.ScalaObject{
    public volatile int bitmap$0;
    public Test();
    public java.lang.String foo();
    public int $tag();
}


JAD says:
public class Test
    implements ScalaObject
{

    public Test()
    {
    }

    public String foo()
    {
        if((bitmap$0 & 1) == 0)
            synchronized(this)
            {
                if((bitmap$0 & 1) == 0)
                {
                    foo = "foo";
                    bitmap$0 = bitmap$0 | 1;
                }
                BoxedUnit _tmp = BoxedUnit.UNIT;
            }
        return foo;
    }

    public int $tag()
    {
        return scala.ScalaObject.class.$tag(this);
    }

    public volatile int bitmap$0;
    private String foo;
}

On Jan 12, 2008 9:15 PM, Steve Yen <[hidden email]> wrote:

> Hi, I'd bet that the following line of code would break in a
> multithreaded app...
>
>   lazy val foo =  ... some init code that must run exactly once ...
>
> So, do I just throw in a synchronized keyword to make it right (2)?
>
>   lazy val foo = synchronized { ... some init code that must run
> exactly once ... }
>
> Or, perhaps, I need to instead write...
>
>   private lazy val foo_i = ... some init code that must run exactly once ...
>   def foo = synchronized { foo_i }
>
> In short, in (2), does the "lazy val" magic part of the code run
> outside the "synchronized"?
>
> Thanks,
> Steve
>