Java Reference
In-Depth Information
far as the SCJD exam is concerned. If you do decide to take this route, execute your lengthier
calls through a separate thread, or worker thread, and then feed your results back into the GUI
using the event dispatcher. For an excellent example of this technique, please visit http://
java.sun.com/products/jfc/tsc/articles/threads/threads2.html .
Caution You must not use the SwingWorker class directly in your assignment. The assignment specifies
that you are only allowed to submit code you write yourself, so submitting the SwingWorker class could
lead to disqualification. You can, however, use the SwingWorker class to learn the techniques needed, then
make your own class(es).
Remember that calling the various setters on a component is not a thread-safe way to get
that event into the event-dispatching queue. This process does generate events, but the event
dispatcher thread does not always handle these.
Updating Components in the Event Dispatcher Thread
So how do you get your events into the event dispatcher thread? You use the SwingUtilities.
invokeAndWait and SwingUtilities.invokeLater methods. The first method, invokeAndWait ,
blocks until the event fires. invokeLater does not block; it simply adds your code to the queue
of events to be fired. The parameter to both of these methods is a Runnable interface. The run
method of the parameter is then called by the event dispatcher.
Threading Best Practices
Here are some general practices that should help you avoid the dark side of threading:
Don't nest locks. If you have two synchronized blocks on two different objects in your
execution path, you're probably heading down the wrong road.
Avoid multithreading with Swing, if possible. It can be argued that multithreading activ-
ities for distributed calls from a Swing front-end, for example, only offer illusionary
responsiveness. That is, just because the GUI appears to respond quickly doesn't mean
that it actually does so. Do you really want your client to think an operation is finished
when in fact it isn't? Does the illusion actually serve a useful purpose in your application?
For threads that are providing lengthy services, it's a good idea to yield occasionally. For
example, if your thread is starting a lengthy process but the user wants to cancel, that
canceling event might not get read until your thread stops executing. By yielding occa-
sionally, you give other threads a chance to slice in at a time that is opportune for your
thread's execution state. It's best to release any locks before yielding.
Search WWH ::




Custom Search