The dilemma of weak listeners in JavaFX

There exists a lot of confusion regarding the life-cycle of JavaFX property listeners and event handlers. For example, many believe that an added property listener must be explicitly removed or memory leaks. To illustrate, here is a quote from the book JavaFX 8: Introduction by Example chapter 3 (page 78):

One last thing to point out is that it is important to clean up listeners by removing them. To remove them you will invoke the removeListener() method [..].

The remove method referred to is Observable.removeListener().

I tried to google all my books and the Internet for an explanation as to why it is “important”. All I could find is even more claims about how “important” it is to remove listeners. But knowing just a handful of Java memory management and reference types, I must conclude that the “importance” is a fallacy.

When a String goes out of scope and becomes unreachable, is it important to delete/nullify the char[] contents that String wraps? No. Just as the String become unreachable and eligible for garbage collection, so to do the char[] contents (actually, sharing the contents across many String instances is not forbidden by JLS and was the cause of bug in the Oracle distributed JDK prior to 1.6). It doesn’t matter if the box know about the cat inside of it, if you throw the box into the ocean. If the box isn’t reachable, nor is the cat.

I spent some time reading through JavaFX source code and I have no reason to expect that malicious code that cause memory leaks has been applied. There is no reason to believe that the listeners of say a text field’s textProperty works any differently than the char[] of a String.

The JavaFX library (which is included in Java SE since version 7 update 6) provide WeakListener and WeakEventHandler as a necessary tooling for developers when they write listeners or event handlers with a different life-cycle than the target. I think that it is these types and a general lack of knowledge in how Java memory management work that has caused all the confusion. To add even more headache into the mix, literature often speak of JavaFX properties as some kind of a JavaBean superset and therefore imply that JavaFX properties work in a strange and unfamiliar sugar coated way, making developers nervous when using or writing them. However, it is wrong to say that JavaFX properties must be written in one or the other way. How they are written is a convention and not part of a specification. JavaFX properties do no magic.

I wrote a StackOverflow answer to bring some clarity.

Leave a Reply

Your email address will not be published. Required fields are marked *