« 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 10:04 PM, Nils Kilden-Pedersen <nilskp@...> wrote:

> On Thu, Jun 5, 2008 at 3:37 PM, David MacIver <david.maciver@...>
> wrote:
>>
>> 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.
>
> I think I know what you mean, but I hope this won't result in instanceof
> check for every access?

It will. instanceof is pretty quick these days. This could be replaced
with a null check, a getClass() == classOf[Lazy] and an additional
level of indirection for the Lazy (have Lazy wrap a Function0 rather
than being abstract).

>> 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.
>
> That bug seems to address two completely different cases. I assume you mean
> case 2?

No, both cases are pretty similar. This would handle both - because
the data is stored on the Lazy instance rather than the enclosing
object it doesn't need to do anything to achieve correctness with
respect to garbage collection.

>> 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.
>
> For the sake of correctness (eliminating dead lock potential) that would be
> a good trade off.
>
> I didn't see an answer to why (int & 1 == 0) was needed instead of a plain
> boolean.

Because if you have multiple lazy values they reuse other parts of the field.

 « Return to Thread: Question on lazy val