If available() returns zero, there are currently no bytes available. According to the documentation you are quoting, this may be for several reasons:
- The pipe was closed.
- The pipe is broken.
- All previously available data (if any) has already been used.
A return value of zero from available() may indicate that an error has occurred, implying that you can never read more data through the pipe in the future, but you cannot say exactly here, because zero can indicate that the third condition is higher. where a lock on InputStream#read() can end up with more data that the corresponding side of OutputStream will push through the handset.
I do not see that it is possible to poll a PipedInputStream with available() until more data appears, because you can never distinguish terminal cases above (first and second) from the reader being more hungry than the writer. Like many streaming interfaces, here you should also try to consume and be prepared for failure. It is a trap; InputStream#read() will block, but only after you lock it while trying to read, you will be able to distinguish that input is no longer being received.
It is not possible to base your consuming actions on available() . If it returns a positive number, there is something that needs to be read, but, of course, even what is available now may not be enough to satisfy your consumer. You can easily control your application if you block the InputStream and block polling with available() . Let InputStream#read() be your only oracle here.
source share