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, and reduce the size of the buffer used to
read bytes from the
InputStream. To show the incremental, non-blocking
update in Figure 12-8, I set the
sleep( ) time to 500 milliseconds and the
buffer size to a mere 80 bytes.
Now you have a URL-loading document and a model for
JTextComponents
that will handle its own threaded loading and can thus be dropped into any
JTextComponent without needing to add any other code to manage its
threaded operation.
public boolean isAlive( ) {
return (readThread != null) && (readThread.isAlive( ));
}
public float getProgress( ) {
return (float) totalBytesRead/length;
}
}
Example 12-10. Document that will not block on URL loading (continued)

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.