While Java provides great I/O abstraction facilities like InputStream and OutputStream, the non-blocking nature of Java NIO often leads to subtle behavior differences in high-level network programming constructs. The case in point is DataInputStream, which enables an application to parse Java primitive types right out of an input stream. However, the stream reading methods in the DataInputStream class exhibit two distinct behaviors when the underline stream is a socket. The following methods are non-blocking:
read(byte[] b)
read(byte[] b, int off, int len)
A non-blocking read means that the first read(byte[] b, int off, int len)may not return the expected len number of bytes. Therefore, the reader program is usually put into a loop to read repeatedly until the len of bytes are read or the EOF is reached.
The primitive type reading methods in DataInputStream are blocking. Take readInt() as an example. That read will block if there are not enough bytes, 4 in this case, in the stream.
Consistency is a good software engineering principle to practice. When using DataInputStream to parse a socket input stream, it is best to always use the primitive type reading methods to avoid confusion of blocking vs non-blocking socket I/O.
No comments:
Post a Comment