Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unblock InputStream.read() on Android?

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.

like image 791
tajmahal Avatar asked Jul 05 '11 08:07

tajmahal


People also ask

Is InputStream read blocking?

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.

What is InputStream in Android?

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.

Why does InputStream read return an int?

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.

What does InputStream read return?

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.


1 Answers

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.

like image 119
Talha Ahmed Khan Avatar answered Oct 18 '22 11:10

Talha Ahmed Khan