Search code examples
javaswingworker

SwingWorker (Thread) doesn't ever die (still lives after reaching "return null;")?


I have implemented a SwingWorker performing some operations in a while loop.

    worker = new SwingWorker<Void, String>()
    {
        public Void doInBackground()
        {
            while(!this.isCancelled())
            {
                //perform operations
            }
            return null;
        }


    };
    worker.execute();

I want to cancel the SwingWorker, thus keeping a reference to "worker" and using it's cancel method.

The cancellation basically works just fine (= "return null;" is reached), but the corresponding thread appears to still live (as shown in my debug-window in eclipse) after cancelling and also takes up resources.

So starting several worker threads and cancelling them keeps them alive after stopping to perform the operations in the while loop and they still accumulate a lot of memory even though they are not used anymore.

I don't want the threads to be alive after they are cancelled, am I missing out on something here?

Any help appreciated!


Solution

  • This is how it is supposed to work. SwingWorker uses thread pool under the hood - it means that you are not directly creating threads by creating SwingWorker. The whole point, is to make those threads "reusable" because thread creation is expensive. So you have bunch of "worker threads" that will execute some tasks for you.

    Be noticed that if you execute another SwingWorker after first one is completed and worker thread (the one you see in the debugger) is idle, the task will be executed by that thread insteed of creating new one.

    Dont worry about the resources. Worker thread pool will shutdown worker threads if they will be not used for some time.