Search code examples
javanetwork-programminginputstreamobjectinputstream

Using ObjectInputStream.available() as eqilivant to Scanner.hasNext()


As it says in ObjectInputStream.available()'s javadoc:

Returns the number of bytes that can be read without blocking.

we should be able to use following code just like Scanner.hasNext()

if (inputStream.available() > 0) {
    Object input = inputStream.readObject();
}

but when i use it even if there is some unread data in stream this condition doesn't get true.

Actually i'm using it in this way in a client-server application and it gets stuck at the if:

    while (continueListening) {
        Object responseObj;
        try {
            if (inputStream.available() == 0) { // this condition is always met
                continue;
            }
            responseObj = inputStream.readObject();
            .
            .
            .

Solution

  • From InputStream JavaDoc:

    Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. [...]

    The available method for class InputStream always returns 0.

    So it's generally not a good idea to rely on the result of available(), like you did. You are looping in case of 0, doing a busy-wait for data. Rather you should use a dedicated thread and just call readObject() which will block until enough data is available or an exception is thrown, e.g. if the connection is closed while reading.

    Scanner.hasNext() might block as well, if the next token has not been read (completely).