开发者

Why is Swing JFrame always reachable?

开发者 https://www.devze.com 2023-02-20 05:48 出处:网络
How come JFrame insta开发者_如何学Pythonnces are always reachable within a Swing application? Won\'t that prevent it from being garbage collected?

How come JFrame insta开发者_如何学Pythonnces are always reachable within a Swing application? Won't that prevent it from being garbage collected?

JFrame frame = new JFrame();
System.out.println(Window.getWindows().length); // says '1'

Calling dispose() doesn't help. It is not even shown.


There is no getWindows method on java.awt.Windows, but there is a Frame.getFrames() method.

But I know that both of them use WeakReference to manage such things.

Basically the idea is that both Window and Frame class has a field called weakThis which is a weakreference to the current frame/window object. Whenever the object needs to be stored(for e.g. in appcontext), the weakThis field is used instead of this. (Weakreferences don't stop gc-ing of objects, in case you didn't knew)

EDIT: Window.getWindows is added in 1.6.


Because the JFrame object has not been garbage collected. Try this:

import java.io.*;
import java.awt.*;
import javax.swing.*;
public class WTest
{
    public static void main(String[] args)
    {
        JFrame jfTmp = new JFrame();
        jfTmp.dispose();
        jfTmp = null;

        System.runFinalization();
        System.gc();

        Window[] arrW = Window.getWindows();
        for(int i = 0; i < arrW.length; i ++)
            System.out.println("[" + i + "]\t" + arrW[i].getClass());
    }
}


This is because you still have a reference to your window, you didn't make the JFrame ready for garbage collection this is done removing the reference to it. For example by setting it to null;

The next example will return 0 if the garbage collector did a cleanup round.

JFrame frame = new JFrame();
frame = null;
System.gc();
System.out.println(Window.getWindows().length);

This is example code, which will work most the time, if the GC is invoked. It is not guaranteed that the System.gc() will invoke the GC. Dont use this in production code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号