Java Reference
In-Depth Information
9.3.2. Progress and Completion Indication
Using a
Future
to represent a long-running task greatly simplified implementing cancella-
tion.
FutureTask
also has a
done
hook that similarly facilitates completion notification.
After the background
Callable
completes,
done
is called. By having
done
trigger a com-
pletion task in the event thread, we can construct a
BackgroundTask
class providing an
onCompletion
hook that is called in the event thread, as shown in
Listing 9.7
.
BackgroundTask
also supports progress indication. The
compute
method can call
setProgress
, indicating progress in numerical terms. This causes
onProgress
to be
called from the event thread, which can update the user interface to indicate progress visually.
To implement a
BackgroundTask
you need only implement
compute
, which is called
in the background thread. You also have the option of overriding
onCompletion
and
onProgress
, which are invoked in the event thread.
Basing
BackgroundTask
on
FutureTask
also simplifies cancellation. Rather than hav-
ing to poll the thread's interrupted status,
compute
can call
Future. is-Cancelled
.
9.3.3.
SwingWorker
We've built a simple framework using
FutureTask
and
Executor
to execute longrun-
ning tasks in background threads without undermining the responsiveness of the GUI.
These techniques can be applied to any single-threaded GUI framework, not just Swing. In
Swing, many of the features developed here are provided by the
SwingWorker
class, in-
cluding cancellation, completion notification, and progress indication. Various versions of
SwingWorker
have been published in
The Swing Connection
and
The Java Tutorial
, and
an updated version is included in Java 6.
9.4. Shared Data Models
Swing presentation objects, including data model objects such as
TableModel
or
TreeModel
, are confined to the event thread. In simple GUI programs, all the mutable state
is held in the presentation objects and the only thread besides the event thread is the main
thread. In these programs enforcing the single-thread rule is easy: don't access the data model
or presentation components from the main thread. More complicated programs may use other