listeners and lambda method reference
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Tue Feb 10 17:18:53 UTC 2015
Hi Sebastien,
the identity of an instance obtained through capture is 'unreliable'. In
case of method references is not unthinkable considering adding an
equals() implementation which takes into account all the parameters to
the bootstrap method used to forge a new instance of the functional
interface, but that's not how things work now. An alternative way to
express the idiom now is:
Listener l = this::propertyChanged;
...
property.addListener(l);
...
property.removeListener(l);
Which will do what you expect (as there's only one capture there).
Maurizio
On 10/02/15 16:53, sebastien deries wrote:
> Hi all,
>
>
>
> While working on memory leak issues in my application, I discovered that I
> had a problem with the way I use lambda reference method.
>
> Here is the problem:
>
>
>
> public class Lambda {
>
> private final Property<Boolean> property;
>
>
>
> public Lambda() {
>
>
>
> property = new SimpleBooleanProperty();
>
>
>
> property.addListener(this::propertyChanged);
>
> property.removeListener(this::propertyChanged);
>
>
>
> property.setValue(true);
>
>
>
> }
>
>
>
> private void propertyChanged(ObservableValue<? extends Boolean>
> notifier, Boolean previous, Boolean next) {
>
> System.out.println(" hello !");
>
>
>
> }
>
>
>
> public static void main(String[] args) {
>
> new Lambda();
>
> }
>
>
>
> }
>
>
>
> In this example, I have a property and want to listen to the property
> changes. When I run this example, the console output says “hello!” whereas
> I removed the listener. I thought that the syntax this::propertyChanged was
> giving me a single instance of ChangeListener, but I was apparently wrong.
>
>
>
> Is this normal?
>
>
>
> Regards
>
>
>
> Seb
>
More information about the lambda-dev
mailing list