MATLAB: Is there a memory leak when I repeatedly open and close the Java GUI objects in MATLAB 6.1 (R12.1) and later versions

awtclasscomponentguijavaleakMATLABmemoryobjectrequestfocusswing

When I create and destroy a Java GUI object repeatedly, as in the following code:
for i=1:1000
f=javax.swing.JFrame('Test for Memory Leak');
f.getContentPane.add(javax.swing.JTextField('text'));
f.pack;
f.setVisible(true);
pause(1.);
f.dispose;
clear f;
end
Memory is consistently being leaked during each iteration.

Best Answer

The code that is showing an example of having a memory leak with Java GUI objects is improper use of Swing. You can avoid having a memory leak by using either of the two following examples:
Example 1 removes the text field from the frame before disposing it:
for i=1:1000
f=javax.swing.JFrame('Test for Memory Leak');
f.getContentPane.add(javax.swing.JTextField('text'));
f.pack;
f.setVisible(true);
pause(1.);
f.getContentPane.remove(0);
f.dispose;
clear f;
end
Example 2 defers packing the frame, making it visible and disposing it to the event dispatch thread. This is consistent with the prescribed use of Swing.
for i=1:1000
f=javax.swing.JFrame('Test for Memory Leak');
f.getContentPane.add(javax.swing.JTextField('text'));
awtinvoke(f,'pack()');
awtinvoke(f,'setVisible(Z)',true);
pause(1.);
awtinvoke(f,'dispose()');
clear f;
end