« Return to Thread: Question on lazy val

Re: Question on lazy val

by David MacIver :: Rate this Message:

Reply to Author | View in Thread

On Thu, Jun 5, 2008 at 9:32 PM, David MacIver <david.maciver@...> wrote:

> On Thu, Jun 5, 2008 at 9:31 PM, Nils Kilden-Pedersen <nilskp@...> wrote:
>> I was looking at the byte code generated for a lazy val, and had a few
>> questions and comments. It appears to be implemented as basic DCL using a
>> volatile int as flag and synchronizing on the class instance.
>> * The int flag does & operation for every access to lazy val. Why, and why
>> not a simple boolean?
>> * Synchronization is on the enclosing instance. Is that deliberate? Worst
>> case, it could cause a hard to find dead-lock. Could a synthetic monitor not
>> be used to eliminate worst case, or am I missing some obvious reason?
>
> The reason in both cases is memory usage - this way there's a fairly
> low overhead for using a lazy val.
>
> I actually have an alternative lazy implementation which would solve
> both these problems that I want to try out some time. It just requires
> me to first get over my fear of the scala compiler.

I suppose I shouldn't make comments like that without explaining myself.

The idea is that we'd have a class scala.runtime.Lazy which is used as
a marker object storing a thunk that evaluates to the lazy value. Then
the laziness implementation can use isInstanceOf[Lazy] to test if it's
been thunked and do synchronization on the Lazy instance rather than
on this.

The main reason I want to do this is that it would provide a nice
solution to https://lampsvn.epfl.ch/trac/scala/ticket/720 - you could
store the data on the Lazy object rather than in the enclosing object.

It might also make lazy arguments easier to do.

In general the result will be that objects with unthunked lazy values
will use a bit more memory but objects with thunked lazy values should
use no more memory than their strict equivalents.

 « Return to Thread: Question on lazy val