4

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 :

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 :

Threads Leak

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 ...

mKorbel
  • 109,525
  • 20
  • 134
  • 319
aleroot
  • 71,077
  • 30
  • 176
  • 213
  • 2
    unrelated to your problem: you _must not_ access view components in doInBackground (that runs off the EDT). Instead, do any view config immediately before calling worker execute or in the worker's constructor. – kleopatra Feb 03 '12 at 11:08

1 Answers1

4

The JavaDoc says:

Schedules this SwingWorker for execution on a worker thread. 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.

Did you try to close and reopen it more than 6 times, to see, whether eventually no new Thread is added? My guess is that you didn't reach the thread pool limit yet.

stryba
  • 1,979
  • 13
  • 19
  • 1
    You are right, no more than 10 threads are allocated, i assume 10 is the limit. But why this threads remain in running state even if they are finished their job ? Is it the normal behaviour ? – aleroot Feb 03 '12 at 09:27
  • 1
    Yes it is, they are basically running to wait for new incoming SwingWorkers, if you use JVisualVM for instance to look at the actual state of the threads you'd probably see them in WAITING state. – stryba Feb 03 '12 at 09:32
  • @aleroot There is more info [here](http://www.jroller.com/ethdsy/entry/swingworker_is_not_a_thread). – Andrey Aug 14 '15 at 16:47