Lambda's and references to their container class
Aleksey Shipilev
aleksey.shipilev at oracle.com
Sun Aug 5 03:50:32 PDT 2012
Hi John,
You might want to read on lambda translation paper [1].
On 08/05/2012 12:44 PM, John Hendrikx wrote:
> Are they like anonymous inner classes created in a static context when they are
> not accessing the parent or do they always keep a reference to the parent?
That depends on the translation strategy, chosen in runtime. In current
scheme, when runtime spins up an inner class when resolving indy,
non-capturing lambdas are not capturing the parent.
I should point out that the translation strategy might change even after
GA, if we figure out more clever (and probably VM-specific) way to
capture arguments.
> externalObject.addListener(new InvalidationListener() {
> public void invalidated() {
> System.out.println("invalidated");
> }
> });
>
> vs.
>
> externalObject.addListener(() -> System.out.println("invalidated"));
>
> Do both hold a reference to their containing instance?
In current scheme, first one does capture parent, second one is not.
Moreover, currently there is only one instance of non-capturing lambda
per call site. Non-capturing lambdas in this sense are more like static
inner class memoized in static final field.
> externalObject.addListener(() -> { someFieldOfParent = true; });
>
> I'm assuming in this case it is forced to capture 'Parent.this' and keep
> a reference around to the parent.
That's right, at this point we are forced to capture parent in one way
or the other.
-Aleksey.
[1] http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html
More information about the lambda-dev
mailing list