Search code examples
javaioblockingnonblocking

available and read: can we actually be nonblocking while using blocking Java I/O?


Based on this question I would like to ask the following. Assuming blocking I/O and I have a piece of code like the following:

byte[] data = new byte[10];
someInputStream.read(data)

This code snippet is going to block in the read call until it has some bytes to read. I'm familiar that read might actually read less bytes and the number of bytes read is going to be returned by the read method.

My question is this. Assume I have:

byte[] data = new byte[10];
if (someInputeStream.available() >= 10) {
       someInputStream.read(data); // ***
}

Is *** line guaranteed to not block? Again, I'm aware that this read might still read less than 10 bytes.


Solution

  • It is guaranteed not to block.

    From the Javadoc for InputStream, looking at the available() method:

    Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

    (Emphasis mine.)

    So it won't block, but (as you say) you might not get the full 10 bytes.

    Note that this is assuming a single thread. If there are multiple threads, then of course another thread might have read from the stream between the available() and the read().