Java Inputstream Blocking Read

Socket InputStream blocks on available() / read()

It is not blocking it is spinning.

Once there is no data available you code might as well read

while (true)
{
if (buffIn.available() > 0) // ALWAYS false now we've run out of data
{
// unreachable
}
}

The loop will never finish. Your test for the minus 1 value will never be executed when there is no data available.

You are seeing available() in the stack trace because that's about the only thing in your loop that's taking up any time, so the chances are, when you create you stack trace, that's where it's going to be.

If you are confident that you will infact get an end-of-file condition (eg if it's TCP and the other end closes the connection) then the available() call is not required at all. Otherwise, you need a different method of determining you have all of the data. For example is the payload size encoded in the first few bytes or something?

when does FileInputStream.read() block?

The answer to your question can be found in the JavaDoc for .read():

This method blocks if no input is yet available.

and

Returns: the next byte of data, or -1 if the end of the file is reached.

So, an empty file will get you an immediate -1 (instead of read() blocking) as

  • there is input available, since the file exists
  • ...but it is empty, so immediate EOF.

The ...No input is yet available... situation could occur eg. when one was to read from a named pipe instead of a plain file, and the other side of the pipe hasn't written anything yet.

Cheers,

Why does reading from Process' InputStream block altough data is available

Why does reading from Process' InputStream block although data is available

It doesn't. The problem here is that data isn't available when you think it is, and that's caused by buffering at the sender.

You can overcome that with fflush() as per @MarkkuK.'s comment, or by telling stdio not to buffer stdout at all, as per yours.



Related Topics



Leave a reply



Submit