capturing (or not) mutable local variables

Peter Levart peter.levart at gmail.com
Sun Nov 21 12:46:29 PST 2010


On Sunday, November 21, 2010 03:08:34 am Neal Gafter wrote:
> Are you saying that if we restrict lambdas to only variables that don't
> change, then it is OK if the variable lifetime is not extended to the
> lifetime of the lambda?  In that case, does the code blow up when you
> invoke a lambda that outlasts the block in which it was created?
> 
> The point of my question is that mutable versus immutable has nothing to do
> with variable lifetime.  Pretending they have anything to do with each
> other is just unnecessarily muddying the the discussion.

That's true. But not entirely. Currently any mutable variable that can be accessed from multiple 
threads (instance or static) can be marked as volatile. Local variables can't be marked as 
volatile. That "restriction" would have to be lifted.

Regards, Peter

> 
> And yes, I do realize that lambda expressions (and the resulting variable
> lifetime extension - no matter if the variables are final or not) are a
> departure from the experience of typical java developers.  I also realize
> that programming with immutable data is a departure from the experience of
> typical java developers.
> 
> On Sat, Nov 20, 2010 at 1:24 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
> > Surely you realize (a) would be a huge departure from the experience of
> > typical java developers.  Who do not read the jls.
> > 
> > Sent from my iPhone
> > 
> > On Nov 20, 2010, at 4:08 PM, Neal Gafter <neal at gafter.com> wrote:
> > 
> > On Sat, Nov 20, 2010 at 1:29 AM, Brian Goetz < <brian.goetz at oracle.com>
> > 
> > brian.goetz at oracle.com> wrote:
> >> If you want to capture a not-effectively-final local variable in a
> >> closure, then one of the following two things has to happen:
> >> a) The lifetime of the variable must be extended to the lifetime of the
> >> closure
> >> b) The lifetime of the closure must be shortened to the lifetime of the
> >> variable.
> > 
> > The JLS doesn't talk about the lifetime of local variables because, like
> > all variables and dynamically allocated objects, they simply cease to
> > exist when they can no longer be referenced.  There would be no need to
> > change that.


More information about the lambda-dev mailing list