Effectively final

Roel Spilker r.spilker at gmail.com
Tue Aug 16 06:50:08 PDT 2011

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. The
array solution will not necessarily be thread safe.

Inside the method and the lambda or anonymous inner class you want to refer
to the local variable as if it is a "normal" variable. This takes a lot of

Instead of allowing access to all mutable local variables, an alternative
approach is to explicitly declare variables to be mutable by lambdas on
anonymous inner classes. One way to do that is to use the `public` keyword.
Other suggestions are to use annotations, so the developer can state hints
about thread safeness or if the lambda should be "completed" before the
declaring method can read the variable.

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.


More information about the lambda-dev mailing list