Java Reference
In-Depth Information
SwingUtilities . isEventDispatchThread , which determines whether the
current thread is the event thread;
SwingUtilities . invokeLater , which schedules a Runnable for execution
on the event thread (callable from any thread);
SwingUtilities . invokeAndWait , which schedules a Runnable task for
execution on the event thread and blocks the current thread until it completes
(callable only from a non-GUI thread);
methods to enqueue a repaint or revalidation request on the event queue (callable
from any thread); and
methods for adding and removing listeners (can be called from any thread, but listen-
ers will always be invoked in the event thread).
The invokeLater and invokeAndWait methods function a lot like an Executor . In
fact, it is trivial to implement the threading-related methods from SwingUtilities using
a single-threaded Executor , as shown in Listing 9.1 . This is not how SwingUtilities
is actually implemented, as Swing predates the Executor framework, but is probably how
it would be if Swing were being implemented today.
The Swing event thread can be thought of as a single-threaded Executor that processes
tasks from the event queue. As with thread pools, sometimes the worker thread dies and is
replaced by a new one, but this should be transparent to tasks. Sequential, single-threaded
execution is a sensible execution policy when tasks are short-lived, scheduling predictability
is not important, or it is imperative that tasks not execute concurrently.
GuiExecutor in Listing 9.2 is an Executor that delegates tasks to SwingUtilities
for execution. It could be implemented in terms of other GUI frameworks as well; for ex-
ample, SWT provides the Display.asyncExec method, which is similar to Swing's in-
vokeLater .
9.2. Short-running GUI Tasks
In a GUI application, events originate in the event thread and bubble up to application-
provided listeners, which will probably perform some computation that affects the present-
ation objects. For simple, short-running tasks, the entire action can stay in the event thread;
for longer-running tasks, some of the processing should be offloaded to another thread.
Search WWH ::




Custom Search