Java Reference
In-Depth Information
modifies the contents of a table, the action listener would update the model and call one of
the fireXxx methods, which would in turn invoke the view's table model listeners, which
would update the view. Again, control never leaves the event thread. (The Swing data mod-
el fireXxx methods always call the model listeners directly rather than submitting a new
event to the event queue, so the fireXxx methods must be called only from the event
thread.)
Figure 9.2. Control Flow with Separate Model and View Objects.
9.3. Long-running GUI Tasks
If all tasks were short-running (and the application had no significant non-GUI portion), then
the entire application could run within the event thread and you wouldn't have to pay any at-
tention to threads at all. However, sophisticated GUI applications may execute tasks that may
take longer than the user is willing to wait, such as spell checking, background compilation,
or fetching remote resources. These tasks must run in another thread so that the GUI remains
responsive while they run.
Swing makes it easy to have a task run in the event thread, but (prior to Java 6) doesn't
provide any mechanism for helping GUI tasks execute code in other threads. But we don't
need Swing to help us here: we can create our own Executor for processing long-running
tasks. A cached thread pool is a good choice for long-running tasks; only rarely do GUI ap-
plications initiate a large number of long-running tasks, so there is little risk of the pool grow-
ing without bound.
We start with a simple task that does not support cancellation or progress indication and that
does not update the GUI on completion, and then add those features one by one. Listing 9.4
shows an action listener, bound to a visual component, that submits a long-running task to
an Executor . Despite the two layers of inner classes, having a GUI task initiate a task in
this manner is fairly straightforward: the UI action listener is called in the event thread and
submits a Runnable to execute in the thread pool.
Search WWH ::




Custom Search