InputStream.available() javadoc:
Returns the number of bytes that can be read (or skipped over) from this input stream without blocking
I think that blocking means that thread from which I called
read()
is blocked (control flow doesn't go further) until thatread()
returns. In this sense I cannot see any scenario in which read() can be called without blocking.Another meaning of blocking may be that if I want to read 3 bytes and have none or just 1 byte available,
read()
would block and wait for more bytes to appear - but I cant't understand it that way b/c then callingread()
and trying to read more than available may cause eternal blocking (just imaging reading 100 bytes from a file of 10 bytes).
In which sense java.io is blocking (1) or (2)?
I cannot simulate a situation when read methods of IO block (in sense (2)) with FileInputStream or ByteArrayInputStream:
// file content is: 1 2 3
FileInputStream myStream = new FileInputStream("d:\\file.txt");
byte[] b = new byte[100];
myStream.read(b);
System.out.println("control reached here?");
System.out.println(Arrays.toString(b));
Output:
reached here?
[122, 100, 122, 120, 118, 122, 120, 32, 118, 122, 120, 118, 32, 122, 120, 118, 32, 122, 118, 99, 122, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Second call myStream.read(b)
would just return -1 also without blocking.
In which scenario does blocking occur?
I thought it occurs if I try to read 5 bytes and there is three. If there is none it means EOF / end-of-stream and -1 is returned (no blocking either).
P.S. I tend to think that java.io is both (1) and (2): it is synchronous (1) and blocking (2), but that blocking is really observed only working with sockets (Socket.getInputStream() / Socket.getOutputStream()
).