Search code examples
javagarbage-collectionlistenerjcomponent

Does Component#removeAll() clean up Observer/Listeners of removed controlls?


I have a container containing JComponents like JButton or JSlider having listeners (onClick, onValueChanged...). Sometimes the containers content is removed with container.removeAll() and refilled with JComponents. The listeners of the components contain references to persistent object instances.

My question is now, does the GC cleanup the listeners of the old components, that were removed?


Solution

  • That depends. The components might be referenced from the other places (even from the listeners themselves). If the listeners were added such that there's no other reference to them, the components might be GCed, however, it's still possible that there are other references in other places in the code to those components.

    In short, there's no way of telling whether the components will get GCed without analyzing the code.

    One way to get an idea whether a component gets GCed or not, is to use PhantomReferences (see PhantomReference)
    In order to check, poll the reference queue you pass as an argument to the PhantomReference.