What triggers the garbage collection of JFrames and other Swing components? In the following code, analyzing the heap during the second Thread.sleep()
reveals that the JFrame instances have not been garbage collected (I'm using VisualVM in particular). Even after manually running the garbage collection in VisualVM the instance still exists. Is the Swing thread somehow holding a reference to these? Interestingly, if the first Thread.sleep(2000)
is removed, the JFrame is collected.
import javax.swing.JFrame;
public class TestDemo {
public static void makeFrame() {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setVisible(true);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
frame.dispose();
frame = null;
}
public static void main(String[] args) {
makeFrame();
System.gc();
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Any ideas why this might be?