I have a thread in which the read()
method of an InputStream
is called in a loop. When there are no more bytes to read, the stream will block until new data arrives.
If I call close()
on the InputStream
from a different thread, the stream gets closed, but the blocked read()
call still remains blocked. I would assume that the read()
method should now return with a value of -1
to indicate the end of the stream, but it does not. Instead, it stays blocked for several more minutes until a tcp timeout occurs.
How do I unblock the close()
call?
Edit:
Apparently, the regular JRE will throw a SocketException
immediately when the stream or socket the blocking read()
call corresponds to is close()
'd. The Android Java runtime which I am using, however, will not.
Any hints on a solution for the Android environment would be greatly appreciated.
According to the java api, the InputStream. read() is described as: 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.
A FileInputStream obtains input bytes from a file in a file system. FilterInputStream. A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.
It returns an int because when the stream can no longer be read, it returns -1. If it returned a byte, then -1 could not be returned to indicate a lack of input because -1 is a valid byte. In addition, you could not return value above 127 or below -128 because Java only handles signed bytes.
Returns. the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Only call read()
when there is data available.
Do something like that:
while( flagBlock )
{
if( stream.available() > 0 )
{
stream.read( byteArray );
}
}
set the flagBlock
to stop the reading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With