garbage collector for JFrame's object

◇◆丶佛笑我妖孽 提交于 2019-12-02 10:20:26

问题


import javax.swing.*;

public class Main
{
    public Main()
    {
        JFrame jf = new JFrame("Demo");
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setSize(100, 100);
        jf.setVisible(true);
    }
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new Main();
            }
        });
        Runtime.getRuntime().gc();

    }

}

I call Runtime.getRuntime().gc(); for explicit garbage collector invoking. But window doesn't dissapear from screen, why doesn't garbage collector reclaim JFrame's object?


回答1:


When a JFrame is created, it registers itself in some internal Swing data structures which allow it to receive events like mouse clicks. This means there is a reference to your object lurking somewhere until you tell Swing to get rid of the window using dispose().




回答2:


Given the invokeLater() call, the call to GC will probably occur 1st1.

BTW - calling Runtime.gc() is generally pointless, the JRE won't GC till it needs to.

  1. E.G.

Output

GC called
Frame visible

Code

package test;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class VisibleFrameGC {

    VisibleFrameGC() {
        JFrame jf = new JFrame("Demo");
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setSize(100, 100);
        jf.setVisible(true);
        System.out.println("Frame visible");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new VisibleFrameGC();
            }
        });
        Runtime.getRuntime().gc();
        System.out.println("GC called");
    }
}



回答3:


The frame is visible and the reference to the object is reachable by at least one of the GUI threads (the Event Dispatch Thread). That is why it isn't garbage collected.


If you want it to disapear, use frame.dispose().



来源:https://stackoverflow.com/questions/9838677/garbage-collector-for-jframes-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!