Doesn't JavaFX (or Java) need additional Java 8 Lambdas support?

When using a lambda expression to add a listener to some JavaFX property, we can fall into the classic trap where we will encounter memory leaks or where the installed listener will not be called:

void init() {
    someProperty.addListener(this::onChanged); // might create a memory leak
    someProperty.addListener(new WeakChangeListener<String>(this::onChanged)); // no memory leak, but the listener won't be called
}

      

The following solution works:

private final ChangeListener<String> changeListener = this::onChanged;

void init() {
    someProperty.addListener(new WeakChangeListener<>(changeListener)); // OK, but requires an extra field + WeakChangeListener
}

      

Is there any other solution to set up a listener with a lambda without much boilerplate?

Edit: Another confusing situation exists, although not related to Lambda expressions, but still related to using weak references with JavaFX, where the following code will not work:

private final ObservableList<Person> persons = FXCollections.observableArrayList();

public ObservableList<Person> getPersons() {
    return FXCollections.unmodifiableObservableList(persons); // a client invoking getPersons().addListener(someListener) won't be notified
}

      

But this code will work (with some extra code template):

private final ObservableList<Person> persons = FXCollections.observableArrayList();
private final ObservableList<Person> immutableList = FXCollections.unmodifiableObservableList(persons); // needed for our clients to be notified

@SuppressWarnings("ReturnOfCollectionOrArrayField") // needed to avoid a warning
public ObservableList<Person> getPersons() {
    return this.immutableList;
}

      

I am using the word "confusing" here because:

  • The working solution is not the one we arrive at first; it is not "natural".
  • When we encounter a problem for the first time, it takes several hours before we understand where the problem comes from.
+3


source to share





All Articles