Effectively final

Per Bothner per at bothner.com
Tue Aug 16 10:58:50 PDT 2011

On 08/16/2011 06:50 AM, Roel Spilker wrote:
> I do agree that there are other ways to handle concurrency and I also think
> that that's the future for scalability.
> But this is not a trivial feature request. It might look like a simple
> boolean check (oh, let's NOT check if the local variable is final) but
> that's not how it works.
> I might be over-simplifying below, but I do think you'll get the point.
> Currently, all local variables "live" in the stack. Especially built-in
> types. When an anonymous inner class refers to the local variable, the
> compiler will actually create a field in the inner class and generate a
> constructor and constructor call passing the value from the stack. This is
> always a valid operation **because** the local variable is final.
> If you want to support mutable local variables capture, a simple stack slot
> will no longer be possible. You need a container object to hold the value so
> modifications can be communicated from and to the inner instance. Currently
> you can basically choose between x[] or AtomicX as standard containers.

Put your 2 paragraphs together and you have your answer:  The container
object *is* the inner class instance.  The compiler translates both 
reads and
writes of the variable to reads and writes of the field.

See "Old closure implementation" here:

A complication (and a difference between Scheme and Java) is handling loops:

int sum = 0;
for (;;) {
    int v = ...;

Putting the sum field in the lambda inner class doesn't work if there
are multiple inner class instances for a captured variable.  In the
general case you might need an extra compiler-generated container object.

> .... These are all cool things. And complicated.
> By restricting the use of local variables to final local variables for now,
> the ways for possible future enhancements remain open.

I tend to agree.  I would prefer to allow mutable local variable
capture, but it makes sense to defer it to post-Java8.
	--Per Bothner
per at bothner.com   per.bothner at oracle.com  http://per.bothner.com/

More information about the lambda-dev mailing list