Closures, too much or too little?

Mark Mahieu markmahieu at
Mon Nov 23 09:35:35 PST 2009

On 23 Nov 2009, at 16:18, Joshua Bloch wrote:

> I'm still not convinced that it's a good idea to allow closure to capture
> shared local variables.  I do (still) like the idea of "auto-finalization"
> (i.e., it's OK for a closure or anonymous class instance creation
> expression) to reference a local variable that's not explicitly labeled
> final if DU/DA-style analysis shows it to be effectively final.  I suspect
> this is the sweet spot.
>             Josh

A good proportion of the annoying cases I encounter with anonymous classes accessing local variables look like this:

int total = 0;
for (...) {
	total += something;
// done with updating total

final int finalTotal = total; // annoying
doSomething(new Whatever() {
	public void execute() {
		// read finalTotal

So for me, a more practical variation of "auto-finalization" would be that the variable only 'becomes' final at the point in the code where the closure appears.  In the above example, I'd even consider it an improvement if I had to (and could) explicitly redeclare 'total' as final.

The other thorny side to all this occurs when the closure actually does want to update the local variable, as you know.  If we don't go some way to making that less awkward, people will continue to use the same workarounds they always have, which also have their costs.

Personally, I quite liked the way that public/@Shared called out the variables as deserving special attention.



More information about the coin-dev mailing list