O'Reilly logo

Database Programming with JDBC & Java, Second Edition by George Reese

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Worker Threads

The book has discussed two constraints that make Swing programming difficult in a multithreaded environment:

  • Changes to models are supposed to occur only in the Swing event queue.

  • Processing in the Swing event queue should be nearly instantaneous.

The reality of the distributed computing world is that things happen asynchronously all over the network, and the network requests made by a client application are rarely instantaneous. You saw an instance of the first problem in your distributed listener pattern. Specifically, you have an alternate thread polling for changes to server objects. Those changes are noted inside your polling thread, but Swing demands that they not be effective until the event-queue thread touches them.

A common technique to dealing with these problems in Swing is called worker threads. A worker thread acts much like the Swing event queue, except that it executes long-lived operations and then notifies the event queue when it should take note of something. You can have any number of worker threads. The more you have, however, the more complex your transaction processing needs to be on the server. For example, the server would need the ability to deal with multiple concurrent connections from the same client. The library shown so far is fairly simplistic, so you will use a single worker thread.

In your application, a WorkerThread object helps support this paradigm. Example 10.4 is a simple class that addresses both of the previous issues.

Example 10-4. A ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required