The AsyncInputStream Class

The AsyncReadSocket class we previously developed had a few problems:

  • This class is specific to the network socket. We could also use an asynchronous I/O class for files, pipes, or any data stream. Ideally, we should have the ability to allow any data source to be asynchronous, not just network sockets.

    There is already a class structure for input from a stream. The top of this hierarchy is the InputStream class. Ideally, we should subclass the InputStream class. We can also benefit from the nested support of the FilterInputStream class and its subclasses.

  • Unlike the TCPServer class, the AsyncReadSocket class does not do a good job at hiding the threading details.

Do we need to develop a new class for this? Doesn’t the InputStream class have a method that supports asynchronous I/O? Although barely mentioned during the development of the AsyncReadSocket class, the InputStream class has the available() method that returns the number of bytes that can be read from the stream without blocking. Although this method sounds useful, it does not always suit our purposes because this method returns the number of bytes that have already been read and are available for processing. On some operating systems, this may include data that has been received at the machine and is being held by the operating system, but that’s not universally true (though it is true on most common operating systems, including those from Microsoft, Apple, Sun, and other Unix vendors).

Hence, ...

Get Java Threads, Second Edition 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.