Note that there are some explanatory texts on larger screens.

plurals
  1. POJava InputStream blocking read
    primarykey
    data
    text
    <p>According to the java api, the <code>InputStream.read()</code> is described as:</p> <blockquote> <p>If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.</p> </blockquote> <p>I have a <code>while(true)</code> loop doing a read and I always get -1 when nothing's sent over the stream. That's expected.</p> <p>My question is when would read() ever block? Since if it doesn't get any data it returns -1. I would expect a blocking read to wait until data is received. If you've reached the end of the input stream, shouldn't read() simply wait for data instead of returning -1?</p> <p>Or does read() only block if there's another thread accessing the stream and your read() cannot access the stream? </p> <hr> <p>Which leads me to my next question. I used to have event listener (provided by my library) that would notify me when data is available. When I was notified I would call <code>while((aByte = read()) &gt; -1)</code> store the byte. I was puzzled when I'd get TWO events in very close time proximity and not all my data was being displayed. It seemed like only the tail end of the second event's data would be displayed and the the rest was missing.</p> <p>I eventually changed my code so that when I get an event I'd called <code>if(inputStream.available() &gt; 0) while((aByte = read()) &gt; -1)</code> store the byte. Now it worked properly and all my data was displayed.</p> <p>Can someone explain this behavior? The <code>InputStream.available()</code> is said to return the number of bytes you can read before blocking the next caller (of the stream?). Even if I don't use .available() I would expect the read of the first event to just block the read of the second event, but not erase or consume too much stream data. Why would doing this cause not all of my data to be displayed?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload