简体   繁体   English

多次实例化时SwingWorker线程/内存泄漏

[英]SwingWorker threads/memory leak when instantiated multiple times

I have a JFrame that shows a preview content, since the loading of preview data could take several times i decided to put the loading operation into a SwingWorker, here's a code sample : 我有一个显示预览内容的JFrame,因为加载预览数据可能需要几次我决定将加载操作放入SwingWorker,这是一个代码示例:

public void setPreviewContent(final String content) {

SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

    @Override
    protected Void doInBackground() throws Exception {

        frame.setCursor(java.awt.Cursor.getPredefinedCursor(
            java.awt.Cursor.WAIT_CURSOR));
        //DO My Work
        return null;
    }

    @Override
    protected void done() {
         frame.setCursor(java.awt.Cursor.getPredefinedCursor(
         java.awt.Cursor.DEFAULT_CURSOR));
    }
};
worker.execute();
}

My frame it is initialized each time that is shown and is disposed each time that is closed with : 我的框架每次显示时都会初始化,每次关闭时都会被处理:

frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

After the initialization and that is show the setPreviewContent() method is called and it work properly, the only problem is that each time i close and reopen the preview frame a Daemon Thread is created and is left running : 在初始化之后,显示setPreviewContent()方法被调用并且它正常工作,唯一的问题是每次我关闭并重新打开预览帧时,会创建一个守护程序线程并保持运行:

线程泄漏

As you can see soon a huge number of threads remain in running state, causing a leak. 正如您所见,很多线程仍处于运行状态,导致泄漏。 How can i resolve the problem ? 我该如何解决这个问题?

If i use a standard Thread i don't have this problem ... 如果我使用标准螺纹我没有这个问题...

The JavaDoc says: JavaDoc说:

Schedules this SwingWorker for execution on a worker thread. 安排此SwingWorker在工作线程上执行。 There are a number of worker threads available. 有许多工作线程可用。 In the event all worker threads are busy handling other SwingWorkers this SwingWorker is placed in a waiting queue. 如果所有工作线程都忙于处理其他SwingWorkers,则将SwingWorker置于等待队列中。

Did you try to close and reopen it more than 6 times, to see, whether eventually no new Thread is added? 您是否尝试关闭并重新打开它超过6次,看看是否最终没有添加新线程? My guess is that you didn't reach the thread pool limit yet. 我的猜测是你还没达到线程池限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM