
Code Models That Don’t Block #93
Chapter 12, Miscellany
|
465
HACK
in whether you want the Runnable executed immediately or in a few milli-
seconds, and whether you’re willing to handle an
InterruptedException—
you can put the code in the worker back on the event-dispatch thread. This
scheme is effectively a callback method, but instead of being concerned
about being called from some event, you’re interested in ensuring you’re
called by a given thread, namely the event-dispatch thread.
In the
doRun( ) implementation, you’ll notice that there’s a flag for whether
or not to use a worker. The blocking version doesn’t, and doesn’t need to,
since it’s already being called from the event-dispatch thread. The non-
blocking version does, but it uses a worker only to reset the contents of the
text area after downloading the contents of the URL:
final StringBuffer finalSBuf = sbuf;
Thread worker = new Thread( ) {
public void run ( ) {
contentArea.setText (finalSBuf.toString( ));
contentArea.setCaretPosition(0);
}
};
SwingUtilities.invokeLater (worker);
Notice how a final variable is used for the StringBuffer.
The anonymous inner thread can see class and instance vari-
ables but not local variables like
sbuf. It can, however, see a
final local variable, so that’s what you pass in.
H A C K
#93
Code Models That Don’t Block Hack #93
Models should know that they’re doing work on another thread.
You already know how to keep ...