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
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 bySwingWorker
.If you want more control, you can also pass the
SwingWorker
instance to anExecutor
.Just check SwingWorker and Executor javadoc for further information.
Besides,
SwingWorker.cancel()
is not supposed to be called fromdoInBackground()
but rather from another thread, generally the EDT, e.g. when user clicks a Cancel button in a progress dialog.You need to add
Thread.sleep(1)
calls in your doInBackground() code every so often. In your sleep catch blocks, addreturn
. I had the same problem, and this worked like a charm.Source: https://blogs.oracle.com/swinger/entry/swingworker_stop_that_train
FYI for anyone passing through: when a SwingWorker is canceled, done() is called before doInBackground() returns.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6826514
Jeff
There is a
cancel()
method. Your code would have to pay attention to that. If it keeps running after an exception, it would appear that you code is ignoring an exception that it shouldn't be.Till The SwingWoker it fixed http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6826514 Here a simple (tested) version with the basic (similar) functions then SwingWoker
as jzd montioned, there is method cancel(boolean mayInterruptIfRunning); for exapmle
EDIT: with cancel(true); you have to (always) cautgh an exception
java.util.concurrent.CancellationException