Skip to Main Content
Java Threads, 3rd Edition
book

Java Threads, 3rd Edition

by Scott Oaks, Henry Wong
September 2004
Intermediate to advanced content levelIntermediate to advanced
362 pages
11h 24m
English
O'Reilly Media, Inc.
Content preview from Java Threads, 3rd Edition

Chapter 7. Threads and Swing

The Swing classes in Java are not threadsafe; if you access a Swing object from multiple threads, you run the chance of data corruption, hung GUIs, and other undesirable effects. To deal with this situation, you must make sure that you access Swing objects only from one particular thread. We saw some examples of this in previous chapters; this chapter explains the details of how threads interact with Swing. The general principles of this chapter apply to other thread-unsafe objects: you can handle any thread-unsafe class by accessing it in a single thread in much the same way as Swing objects must be accessed from a special thread.

We’ll start with a general discussion of the threads that Swing creates automatically for you, and then we’ll see how your own threads can interact with those threads safely. In doing so, we’ll (finally) explain the last pieces of our typing program.

If you’re interested in the general case of how to deal with a set of classes that are not threadsafe, you can read through the first section of this chapter for the theory of how this is handled, then review our example in Chapter 10 to see the theory put into practice.

Swing Threading Restrictions

A GUI program has several threads. One of these threads is called the event-dispatching thread. This thread executes all the event-related callbacks of your program (e.g., the actionPerformed() and keyPressed() methods in our typing test program). Access to all Swing objects must occur ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Performance: The Definitive Guide

Java Performance: The Definitive Guide

Scott Oaks
Java Concurrency, 2/e

Java Concurrency, 2/e

Douglas Schmidt
Java Swing, 2nd Edition

Java Swing, 2nd Edition

Dave Wood, Robert Eckstein, Marc Loy, James Elliott, Brian Cole

Publisher Resources

ISBN: 0596007825Supplemental ContentErrata Page