To cancel a running background task, invokeSwingWorker.cancel
The task must cooperate with its own cancellation. There are two ways it can do this:
- By terminating when it receives an interrupt. This procedures is described in Interrupts in Concurrency.
- By invoking
SwingWorker.isCanceled
at short intervals. This method returnstrue
ifcancel
has been invoked for thisSwingWorker
.The
cancel
method takes a singleboolean
argument. If the argument istrue
,cancel
sends the background task an interrupt. Whether the argument istrue
orfalse
, invokingcancel
changes the cancellation status of the object totrue
. This is the value returned byisCanceled
. Once changed, the cancellation status cannot be changed back.The
Flipper
example from the previous section uses the status-only idiom. The main loop indoInBackground
exits whenisCancelled
returnstrue
. This will occur when the user clicks the "Cancel" button, triggering code that invokescancel
with an argument offalse
.The status-only approach makes sense for
Flipper
because its implementation ofSwingWorker.doInBackground
does not include any code that might throwInterruptedException
. To respond to an interrupt, the background task would have to invokeThread.isInterrupted
at short intervals. It's just as easy to useSwingWorker.isCancelled
for the same purpose
Note: Ifget
is invoked on aSwingWorker
object after its background task has been cancelled,java.util.concurrent.CancellationException
is thrown.