
Code Models That Don’t Block #93
Chapter 12, Miscellany
|
469
HACK
In this case, all the loading is done in a
run( )
method, so the constructor
simply creates a
Thread
called
readThread
to wrap the
run( )
, starts the thread,
and then returns, freeing up the event-dispatch thread almost immediately.
So, now it’s up to
readThread to read the stream and load its contents into
the
Document. As in the blocking version (Example 12-9), it reads bytes into a
buffer, but instead of building a big
StringBuffer with which to do a mass-
insert, it uses
Document’s insertString( ) method to put each bufferful into
the document. Since
insertString( ) will cause the model to fire off events,
this will provide for a constant updating of the view; that’s why this version
calls
insertString( ) each time through the loop instead of once at the bot-
tom, as the blocking version did. However,
insertString( ) is a Swing
method, meaning it’s thread-unsafe, so you can’t call it directly from the
readThread. Instead, you set up a worker and use SwingUtilities.
invokeLater( )
to put the insertString( ) call, and only that call, back onto
the event-dispatch thread.
Running the Code
If you have a fast Internet connection, it is possible that you’ll load the data
so fast that you don’t mind the blocking or you can’t see the incremental
updating of the non-blocking version. To make this more dramatic, increase
the time that each model
sleep( )s, ...