I'm currently investigating a memory leak in one of our applications. After further investigation, I came up with a test of two simple java swing applications that sit idle for almost 14 hours. Both applications consist of 30 JButtons.
The 1st application is using a strong reference for its action listener:
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
The 2nd application is using a weak reference for its action listener:
jButton1.addActionListener(new WeakActionListener(new MyActionListener(), this.jButton1))
Here's the WeakActionListener implementation:
public class WeakActionListener implements ActionListener {
private WeakReference weakListenerReference;
private Object source;
public WeakActionListener(ActionListener listener, Object source) {
this.weakListenerReference = new WeakReference(listener);
this.source = source;
}
public void actionPerformed(ActionEvent actionEvent) {
ActionListener actionListener = (ActionListener) this.weakListenerReference.get();
if(actionListener == null) {
this.removeListener();
} else {
actionListener.actionPerformed(actionEvent);
}
}
private void removeListener() {
try {
Method method = source.getClass().getMethod("removeActionListener", new Class[] {ActionListener.class});
method.invoke(source, new Object[] {this});
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
I profile both applications using JConsole for 14 hours. I just leave them idle for that time frame. It shows that both applications either using weak reference or strong reference have an increasing memory heap consumption over time.
My question is, is this a bug in Java Swing API? What are the other alternatives in resolving this kind of memory leak?
Thanks in advance!