0

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?

spfrommer
  • 158
  • 7
  • Since you say it might be related to the `Thread.sleep`, you might be able to get it to collect by calling `Thread.join` – Norbert van Nobelen Mar 15 '16 at 23:00
  • A good principle is *"Wonder about(/investigate) GC when you see `OutOfMemoryError` - not before!"* It is likely those objects would have been GC'd long before OOME, but retained for a great while yet. – Andrew Thompson Mar 15 '16 at 23:10
  • @VinceEmigh I also manually forced a garbage collection through VisualVM--same result. – spfrommer Mar 15 '16 at 23:10
  • @NorbertvanNobelen Doesn't seem to help. – spfrommer Mar 15 '16 at 23:14
  • @AndrewThompson Possibly, I'm just curious as to whether this was a case of delayed garbage collection or the Swing thread holding on to references somewhere. – spfrommer Mar 15 '16 at 23:22
  • 1
    Possible duplicate of [*Remove Top-Level Container on Runtime*](http://stackoverflow.com/q/6309407/230513); see also [*Initial Threads*](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html). – trashgod Mar 15 '16 at 23:29
  • I think maybe due to the sleep, the frame is actually displayed which causes some references to be created on the UI thread and in native code, without the sleep it could be disposed before it is even visible and rendered. Also small note: you don't have to call frame = null before leaving the frame. – NickL Jan 06 '17 at 20:22

0 Answers0