To cancel a running background task, invokeSwingWorker.cancelThe 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.isCanceledat short intervals. This method returnstrueifcancelhas been invoked for thisSwingWorker.The
cancelmethod takes a singlebooleanargument. If the argument istrue,cancelsends the background task an interrupt. Whether the argument istrueorfalse, invokingcancelchanges the cancellation status of the object totrue. This is the value returned byisCanceled. Once changed, the cancellation status cannot be changed back.The
Flipperexample from the previous section uses the status-only idiom. The main loop indoInBackgroundexits whenisCancelledreturnstrue. This will occur when the user clicks the "Cancel" button, triggering code that invokescancelwith an argument offalse.The status-only approach makes sense for
Flipperbecause its implementation ofSwingWorker.doInBackgrounddoes not include any code that might throwInterruptedException. To respond to an interrupt, the background task would have to invokeThread.isInterruptedat short intervals. It's just as easy to useSwingWorker.isCancelledfor the same purpose
Note: Ifgetis invoked on aSwingWorkerobject after its background task has been cancelled,java.util.concurrent.CancellationExceptionis thrown.