Do weakly referenced listeners have to be removed in order for garbage collection to occur? Is it good practice to remove the listeners even if they are weakly referenced or can we count on the garbage collector to deal with them appropriately?
Do weakly referenced listeners have to be removed in order for garbage collection to
Share
You don’t have to remove weak listeners manually in order for them to be garbage collected. Not unregistering listeners cause most of the memory leaks you’ll encounter so using weak listeners can dramatically improve your programs stability.
However, to keep a weak listener from getting removed before you are ready, you have to have at least one strong reference to it (or use an instance method). That usually means whatever registered the listener needs to hold onto it until that parent class references have been removed. That makes the listener last as long as the instance owning the listener which is the most common case with components.
There are cases where you’ll have to manage listeners and that is if you plan on not listening for the entire life of the parent. Possibly where you want to remove the listener then add it back at a later time, not common, but it happens. That’s where weak listeners don’t have any advantage over strong reference listeners.
The garbage collector will remove weak listeners quickly once the strong reference to it is removed. Weak listeners make cleaning up much simpler. While people are cautious, as I’m sure you’ll hear, because weak listeners are fairly new to UI frameworks. When GC was added to mainstream languages most people were overly cautious about that too.
We rely on the GC to clean up memory, that works and makes for much stabler code, and these days people don’t call that sloppy code. Weak listeners aren’t any different.