<Swing Dev> Is the following code supposed to leak?

Roman Kennke roman at kennke.org
Sat Aug 20 07:30:03 UTC 2011


Hi Clemens,

> When running the Notepad-Demo shipped with the JDK on
> caciocavallo-web, I noticed memory leaks caused by
> PropertyChangeListeners added to Actions defined in DefaultEditorKit.
> Those actions are referenced by a static field (defaultActions).
> 
> I was able to distill the problem down to the following testcase, is
> the following code really supposed to leak memory:
> 
>  while(true) {
>        final byte[] b = new byte[1000000];
>         
>        new JTextArea().getActions()[0].addPropertyChangeListener(new
> PropertyChangeListener() {
>             public void propertyChange(PropertyChangeEvent evt) {
>                b[0] = 0; //Listener will live forever, and so Objects
> referenced from here
>             }
>             });
>     }

You keep creating and adding new listeners without ever removing them.
Of course this is going to leak. It's not even related to the fact that
the listener references the array (although that could play a role in
more complicated leaking scenarios).

Roman





More information about the swing-dev mailing list