Lambda's and references to their container class
John Hendrikx
hjohn at xs4all.nl
Sun Aug 5 01:44:46 PDT 2012
I'm wondering if someone could explain how close Lambda's are to
anonymous inner classes when it comes to retaining a reference to the
class (parent/container) where they are instantiated within. 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?
For example:
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?
What if a field of the parent was accessed instead of doing a System.out?
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.
So, I'm curious if passing a 'listener' like this to an external object
will prevent garbage collection of the container class for Lambda's in
these situations. Anonymous inner classes do this currently and it can
cause surprises when listening to objects much longer lived than the
container class.
--John
More information about the lambda-dev
mailing list