Search code examples
javamultithreadingswingswingworkercancellation

How cancel the execution of a SwingWorker?


Currently I have two SwingWorker threads doing job on background. If an exception occurs, the method stop to work, but the thread still runnig.

How I do to stop the execution and kill the thread of the doInBackground() if an exception occurs?

this.cancel(true) don't destroy/close the thread. How can I achieve this?

@Override
protected Boolean doInBackground() throws Exception {
        try {
            while (true) {
                //some code here                   
                return true;
            }
        } catch (Exception e) {       
            this.cancel(true); //<-- this not cancel the thread               
            return false;
        }
    }

I see these threads in the debug of Netbeans.

'AWT-EventQueue-0' em execução
'AWT-Windows' em execução
'SwingWorker-pool-1-thread-1' em execução
'SwingWorker-pool-1-thread-2' em execução

//*em execução = in execution

Solution

  • By default, SwingWorker reuses worker threads, so it is perfectly normal that, even though, doInBackground() has returned, to still see the thread that executed your method.

    You can identify this fact by looking at the thread names, as reported by NetBeans: SwingWorker-pool-1-thread-1, where that pool is managed by SwingWorker.

    If you want more control, you can also pass the SwingWorker instance to an Executor.

    Just check SwingWorker and Executor javadoc for further information.

    Besides, SwingWorker.cancel() is not supposed to be called from doInBackground() but rather from another thread, generally the EDT, e.g. when user clicks a Cancel button in a progress dialog.