Java Reference
In-Depth Information
9.1.1. Sequential Event Processing
GUI applications are oriented around processing fine-grained events such as mouse clicks,
key presses, or timer expirations. Events are a kind of task; the event handling machinery
provided by AWT and Swing is structurally similar to an Executor .
Because there is only a single thread for processing GUI tasks, they are processed sequen-
tially—one task finishes before the next one begins, and no two tasks overlap. Knowing this
makes writing task code easier—you don't have to worry about interference from other tasks.
The downside of sequential task processing is that if one task takes a long time to execute,
other tasks must wait until it is finished. If those other tasks are responsible for responding
to user input or providing visual feedback, the application will appear to have frozen. If a
lengthy task is running in the event thread, the user cannot even click “Cancel” because the
cancel button listener is not called until the lengthy task completes. Therefore, tasks that ex-
ecute in the event thread must return control to the event thread quickly. To initiate a lon-
grunning task such as spell-checking a large document, searching the file system, or fetch-
ing a resource over a network, you must run that task in another thread so control can return
quickly to the event thread. To update a progress indicator while a long-running task executes
or provide visual feedback when it completes, you again need to execute code in the event
thread. This can get complicated quickly.
9.1.2. Thread Confinement in Swing
All Swing components (such as JButton and JTable ) and data model objects (such as
TableModel and TreeModel ) are confined to the event thread, so any code that accesses
these objects must run in the event thread. GUI objects are kept consistent not by synchron-
ization, but by thread confinement. The upside is that tasks that run in the event thread need
not worry about synchronization when accessing presentation objects; the downside is that
you cannot access presentation objects from outside the event thread at all.
The Swing single-thread rule : Swing components and models should be created, modified,
and queried only from the event-dispatching thread.
As with all rules, there are a few exceptions. A small number of Swing methods may be
called safely from any thread; these are clearly identified in the Javadoc as being thread-safe.
Other exceptions to the single-thread rule include:
Search WWH ::




Custom Search