Download the JDK
Search the Tutorials
Hide the TOC
Trail: Creating a GUI with JFC/Swing
Lesson: Concurrency in Swing
Section: Worker Threads and SwingWorker
Concurrency in Swing
Initial Threads
The Event Dispatch Thread
Worker Threads and SwingWorker
Simple Background Tasks
Tasks that Have Interim Results
Canceling Background Tasks
Bound Properties and Status Methods
Home Page > Creating a GUI with JFC/Swing > Concurrency in Swing
« Previous • Trail • Next »
Canceling Background Tasks

> To cancel a running background task, invoke `SwingWorker.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 returns `true` if `cancel` has been invoked for this `SwingWorker`.

> The `cancel` method takes a single `boolean` argument. If the argument is `true`, `cancel` sends the background task an interrupt. Whether the argument is `true` or `false`, invoking `cancel` changes the cancellation status of the object to `true`. This is the value returned by `isCanceled`. Once changed, the cancellation status cannot be changed back.

> The `Flipper` example from the previous section uses the status-only idiom. The main loop in `doInBackground` exits when `isCancelled` returns `true`. This will occur when the user clicks the "Cancel" button, triggering code that invokes `cancel` with an argument of `false`.

> The status-only approach makes sense for `Flipper` because its implementation of `SwingWorker.doInBackground` does not include any code that might throw `InterruptedException`. To respond to an interrupt, the background task would have to invoke `Thread.isInterrupted` at short intervals. It's just as easy to use `SwingWorker.isCancelled` for the same purpose

> > Note: If `get` is invoked on a `SwingWorker` object after its background task has been cancelled, `java.util.concurrent.CancellationException` is thrown.

« Previous • Trail • Next »
Previous page: Tasks that Have Interim Results
Next page: Bound Properties and Status Methods