Lambda Expressions and listener references?


I am using Lambda expressions more and more…

So from the Vaadin book we have:

layout.addComponent(new Button("Click Me!", event -> event.getButton().setCaption("You made click!"))); So what happens when the window / form / layout that the button is on is closed / removed from the UI?

Will it ever get freed (i.e. garbage collected)? I never call button.removeClickListener, so is the list of click listeners referencing an object (not sure which object), that will stop the list / button / layout etc from getting garbage collected because it is still referenced from somewhere?

I imagine the question applies to any listener framework with Java 8 lamdas… you don’t remove the listener so therefore things stay around (although not visible). Basically is it a case of the obsolete reference problem?

Does Java 8 lambda’s somehow get around it, or is it solved some other way, or just not worried about?



Event listeners are held by the component they belong to. When the components is grabage collected, the event listeners can be too (unless some other reference is held to them). You don’t have to explicitely remove event listeners from components.

Java 8 lambdas have the same problem as anonymous classes. If you have a lot of them them, there wil be a lot of class definitions that take up space. These do not get garabage collected as quickly as normal objects. See also