Java Reference
In-Depth Information
Chapter 9. GUI Applications
If you've tried to write even a simple GUI application using Swing, you know that GUI ap-
plications have their own peculiar threading issues. To maintain safety, certain tasks must run
in the Swing event thread. But you cannot execute longrunning tasks in the event thread, lest
the UI become unresponsive. And Swing data structures are not thread-safe, so you must be
careful to confine them to the event thread.
Nearly all GUI toolkits, including Swing and SWT, are implemented as singlethreaded sub-
systems in which all GUI activity is confined to a single thread. If you are not planning to
write a totally single-threaded program, there will be activities that run partially in an applic-
ation thread and partially in the event thread. Like many other threading bugs, getting this
division wrong may not necessarily make your program crash immediately; instead, it could
behave oddly under hard-to-identify conditions. Even though the GUI frameworks themselves
are single-threaded subsystems, your application may not be, and you still need to consider
threading issues carefully when writing GUI code.
9.1. Why are GUIs Single-threaded?
In the old days, GUI applications were single-threaded and GUI events were processed from
a “main event loop”. Modern GUI frameworks use a model that is only slightly different: they
create a dedicated event dispatch thread (EDT) for handling GUI events.
Single-threaded GUI frameworks are not unique to Java; Qt, NextStep, MacOS Cocoa, X Win-
dows, and many others are also single-threaded. This is not for lack of trying; there have been
many attempts to write multithreaded GUI frameworks, but because of persistent problems
with race conditions and deadlock, they all eventually arrived at the single-threaded event
queue model in which a dedicated thread fetches events off a queue and dispatches them to
applicationdefined event handlers. (AWT originally tried to support a greater degree of multi-
threaded access, and the decision to make Swing single-threaded was based largely on experi-
ence with AWT.)
Multithreaded GUI frameworks tend to be particularly susceptible to deadlock, partially be-
cause of the unfortunate interaction between input event processing and any sensible object-
oriented modeling of GUI components. Actions initiated by the user tend to “bubble up” from
the OS to the application—a mouse click is detected by the OS, is turned into a “mouse
click” event by the toolkit, and is eventually delivered to an application listener as a higher
level event such as a “button pressed” event. On the other hand, application-initiated actions
Search WWH ::




Custom Search