如何让AppContext释放AWT组件以便它们可以被垃圾回收? [英] How do I get AppContext to release AWT components so they can be garbage collected?

查看:168
本文介绍了如何让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组件以便它们可以被垃圾回收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆