本文介绍了如何让 AppContext 释放 AWT 组件以便它们可以被垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的团队正在分析我们的 Swing 应用程序,以确保所有不再使用的东西都被垃圾回收.我们遇到了一个奇怪的问题.

My team is working on analyzing our Swing application to make sure everything is being garbage collected when it's no longer being used. We're running into an odd problem.

我们只是打开一个新窗口(JFrame)并关闭它.该框架包含一个 EmptyPanel 类(其中包含一条说明没有数据的短消息)和一个自定义 JMeunBar 类.我们根本不与此交互 - 只需立即关闭窗口即可.

We are simply opening a new window (JFrame) and closing it. This frame contains an EmptyPanel class (which contains a short message saying there is no data) and a custom JMeunBar class. We don't interact with this at all - just close the window immediately.

然后,我们强制进行垃圾回收并进行堆转储.

Then, we force a garbage collection and do a heap dump.

分析堆转储后,JMenuBar 没有被垃圾收集.它从 GC Root sun.awt.AppContext 保持打开状态.

Upon analysis of the heap dump, the JMenuBar isn't being garbage collected. It's being kept open from the GC Root sun.awt.AppContext.

我们如何清理它?或者这是我们出于某种原因不必担心的事情?我们希望努力确保我们的应用程序自行清理干净,但我们也不想在此问题上拖泥带水.

How do we clean this up? Or is this something we don't have to worry about for some reason? We want to be diligent making sure our application cleans up after itself, but we don't want to spin our wheels on this either.

AppContext.mainAppContext 包含一个 HashMap,其中包含一个 BasicPopupMenuUI.MenuKeyboardHelper 实例.在它里面是一个 ComponentInputMapUIResource.menuInputMap,它有这个 JMenuBar 作为一个组件.

AppContext.mainAppContext contains a HashMap which contains a BasicPopupMenuUI.MenuKeyboardHelper instance. Inside this is a ComponentInputMapUIResource.menuInputMap which has this JMenuBar as a component.

推荐答案

如前所述 此处 有许多系统资源必须在 JVM 的正常操作过程中显式释放.图形上下文的 dispose() 方法就是一个例子;父窗口的 dispose() 方法是另一个.在任何一种情况下,资源都可能被正确释放,但您可能会在最终确定之前观察到堆.

As discussed here there are a number of system resources that must be freed explicitly in the normal course of the JVM's operation. The graphics context's dispose() method is one example; the parent window's dispose() method is another. In either, the resource may be correctly released, but you may observe the heap before it has been finalized.

很难概括可以安全忽略的内容,但一种经验方法是在分析器中执行目标.此比较中的前两个图表显示,某种涉嫌保留资源的方法.相比之下,第三张图表显示了平坦的内存使用和垃圾收集活动的周期性峰值.下面是一个视觉上繁忙"的程序的典型锯齿模式,例如这个游戏.请注意,每个循环都会返回基线.

It's hard to generalize about what can be safely ignored, but one empirical approach is to exercise the target in a profiler. The first two graphs in this comparison show a small but steady increase in memory consumed by a certain method that is suspected of retaining resources. In contrast, the third chart shows flat memory use with periodic spikes of garbage collection activity. Below is the typical saw-tooth pattern of a visually "busy" program such as this game. Note that each cycle returns to the baseline.

这篇关于如何让 AppContext 释放 AWT 组件以便它们可以被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 02:12