Effectively final

Tim Fox timvolpe at gmail.com
Fri Jul 29 04:31:09 PDT 2011


Hello All,

I was just looking at Brian Goetz's proposal "State of the Lambda". 
Firstly, I'd like to say that adding lambdas/closures to the Java 
language will be a huge win. However I do have some concerns with the 
proposal that lambdas will not be able to modify captured local variables.

To give some background, the angle I am coming from is someone who is 
writing an asynchronous programming framework which makes have use of 
callbacks. Similar frameworks exist in other languages, e.g. node.js is 
a very popular one right now.

AIUI most languages which support closures/lambdas do allow local 
variables to be mutated from within the closure. This allows a local 
variable to co-ordinate the results from different callbacks and allows 
asynchronous control flow to be composed in a clear and simple way.

I fully understand that if multiple threads are involved then allowing 
such access can result in race conditions. However these frameworks 
typically guarantee that all access to a co-ordinated set of objects is 
accessed by at most one thread (event loop / reactor pattern), so race 
conditions are not an issue.

Right now, because of lack of lambdas/closures such a style of 
programming is clunky using Java (since anonymous classes are required), 
but even with the proposed lambdas it would still be difficult since it 
would require co-operating closures to interact via final object 
references (e.g. using AtomicLong, AtomicReference or some other 
object), which will result in ugly and clunky code (compared to other 
programming languages). This seems really unnecessary when the framework 
can guaranteed the same thread always executes the code.

IMHO it would be nice, and a big win for such a programming style, to, 
perhaps default to final variable access only (for safety with multiple 
threads), but to allow this rule to be relaxed when the framework can 
guarantee that thread safety is not a concern, thus allowing much 
simpler code.




More information about the lambda-dev mailing list