Lambda expressions keeping a reference to the enclosing instance

Markus Keller markus_keller at ch.ibm.com
Fri Nov 8 07:37:04 PST 2013


Dan Smith wrote on 2013-10-30 20:36:45:
> http://cr.openjdk.java.net/~dlsmith/jsr335-0.7.0/

15.27.4 defines the value of a lambda expression, but misses to define an 
important property of the lambda instance: Can/must/will the lambda 
instance contain a reference to the enclosing instance (if one exists)? 
15.27.4 point 4 implicitly makes such a reference to the outer "this" 
necessary iff the lambda body actually contains such a reference. But it 
is unclear whether the lambda always contains this reference.

For the similar situation with inner classes, JLS7 clearly specifies that 
the inner class constructor always gets a reference to the enclosing 
instance (8.1.3, 13.1, 15.9.3). For methods references, the new 15.28.3 
also spells out the forms for which a target reference is retained.

For lambda expressions, current Java 8 beta implementations seem to avoid 
the reference by declaring the synthetic lambda$x method declaration as 
static if possible.

Request: Specify that a reference to the enclosing instance of a lambda 
expression is only retained if necessary. That makes the system behavior 
well-defined and makes memory leaks (via lambda expressions that leak a 
reference to the enclosing instance) deterministic like in the rest of the 
Java language.

Markus

--
References:

jsr335-0.7.0 15.27.4 Point 4: "The method's body has the effect of 
evaluating the lambda body, if it is an expression, or of executing the 
lambda body, if it is a block;"

JLS7 8.1.3 says about inner classes:
"An instance i of a direct inner class C of a class O is associated with 
an instance of O, known as the immediately enclosing instance of i. The 
immediately enclosing instance of an object, if any, is determined when 
the object is created (§15.9.2)."

JLS7 13.1 says about inner member classes:
"In addition, the constructor of a non-private inner member class must be 
compiled such that it has as its first parameter, an additional implicit 
parameter representing the immediately enclosing instance (§8.1.3)."

JLS7 15.9.3 says about anonymous classes:
"Otherwise, the immediately enclosing instance of i with respect to S is 
the first argument to the constructor".



More information about the lambda-spec-comments mailing list