Java Reference
In-Depth Information
that appeared consecutively in the stream. Similarly, if two threads are
writing to the same stream then the bytes written in each write opera-
tion will be sent consecutively to the stream, not intermixed at random
points.
The character streams use a different synchronization strategy from
the byte streams. The character streams synchronize on a protected
lock field which, by default, is a reference to the stream object itself.
However, both Reader and Writer provide a protected constructor that
takes an object for lock to refer to. Some subclasses set the lock field
to refer to a different object. For example, the StringWriter class that
writes its character into a StringBuffer object sets its lock object to be
the StringBuffer object. If you are writing a reader or writer, you should
set the lock field to an appropriate object if this is not appropriate. Con-
versely, if you are extending an existing reader or writer you should al-
ways synchronize on lock and not this .
In many cases, a particular stream object simply wraps another stream
instance and delegates the main stream methods to that instance, form-
ing a chain of connected streams, as is the case with Filter streams.
In this case, the synchronization behavior of the method will depend on
the ultimate stream object being wrapped. This will only become an is-
sue if the wrapping class needs to perform some additional action that
must occur atomically with respect to the main stream action. In most
cases filter streams simply manipulate data before writing it to, or after
reading it from, the wrapped stream, so synchronization is not an issue.
Most input operations will block until data is available, and it is also pos-
sible that output stream operations can block trying to write datathe ul-
timate source or destination could be a stream tied to a network sock-
et. To make the threads performing this blocking I/O more responsive
to cancellation requests an implementation may respond to Thread in-
terrupt requests (see page 365 ) by unblocking the thread and throw-
ing an InterruptedIOException . This exception can report the number of
bytes transferred before the interruption occurredif the code that throws
it sets the value.
For single byte transfers, interrupting an I/O operation is quite straight-
forward. In general, however, the state of a stream after a thread using
 
Search WWH ::




Custom Search