小编rya*_*aaa的帖子

java垃圾收集在对话框中

*当我尝试在JFrame中创建一个按钮时,我现在遇到一个非常奇怪的java GC问题,当我单击该按钮时,它会显示一个需要处理并显示一些图像并需要近200M内存的JDialog.但问题是当我关闭对话框并重新打开它时,有时它会导致java.lang.OutOfMemoryError.(不是每次都)

试图解决这个问题,我简化了这个问题并做了一些实验,这让我更加困惑.

我在"实验"中使用的代码如下所示.当我单击框架中的按钮时,我为整数数组分配160M内存,并显示一个对话框但是如果我关闭对话框并重新打开它,则会出现OutOfMemoryError.我调整代码,结果是:

  1. 如果我不创建对话框并显示它,没有内存问题.
  2. 如果我添加一个调用System.gc()的windowsCloseListener到对话框,没有内存问题.
  3. 如果我在run()方法中调用System.gc(),则显示内存问题.

    public class TestController {
      int[] tmp;
    
      class TDialog extends JDialog {
        public TDialog() {
          super();
          this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
          // If I uncommment this code, OutOfMemoryError seems to dispear in this situation
          // But I'm sure it not a acceptable solution
          /*
          this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              System.out.println("windowsclose");
              TDialog.this.dispose();
              System.gc();
            }
          });
          */
        }
      }
    
      TDialog dia;
    
      public void run() {
        // If I do System.gc() here, OutOfMemoryError still exist …
    Run Code Online (Sandbox Code Playgroud)

java swing garbage-collection memory-leaks

7
推荐指数
1
解决办法
633
查看次数

标签 统计

garbage-collection ×1

java ×1

memory-leaks ×1

swing ×1