views:

145

answers:

2

What does InputStream.available() do in Java? I read the documentation, but I still cannot make it out.

The doc says:

Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream. The next caller might be the same thread or or another thread.

The available method for class InputStream always returns 0.

What do they mean by blocking? Does it just mean a synchronized call?

And most of all, what is the purpose of the available() method?

+2  A: 

In InputStreams, read() calls are said to be "blocking" method calls. That means that if no data is available at the time of the method call, the method will wait for data to be made available.

The available() method tells you how many bytes can be read until the read() call will block the execution flow of your program. On most of the input streams, all call to read() are blocking, that's why available returns 0 by default.

However, on some streams (such as BufferedInputStream, that have an internal buffer), some bytes are read and kept in memory, so you can read them without blocking the program flow. In this case, the available() method tells you how many bytes are kept in the buffer.

Vivien Barousse
BufferedInputStream.available() tells you how many bytes can be read without blocking. This is the *sum* of the number of bytes already in the buffer and the avaiable() result of the nested input stream. Note also that available() always returns zero for an SSL socket.
EJP
What I didn't quite understand is what is the *use* of knowing this. I really, can't see why should I care, i.e. I can't see where and when in mu app I could find it some use. Of course, it's pretty obvious, that I am being ignorant, but that's is for my *lack* of experience.
Albus Dumbledore
As I said above, there are very few useful uses. You have to know you're dealing with a stream that will deliver a non-zero answer and then you have to have a use for the result.
EJP
+4  A: 

Blocking doesn't relate to threading or synchronisation here. Instead it relates to blocking IO (see this for more info). If you issue a request to read 4 bytes, and the channel only has 3 available, a blocking call will wait (or block) until that 4th byte has turned up (or the channel is closed, throws an exception etc.)

So why use available() ? So you can determine how many bytes to read, or determine whether you're going to block.

Note that Java has non-blocking IO capabilities as well. See here for more details

Brian Agnew
I stumbled upon this question and am now wondering, can I use available() to solve my own problem, without resorting to NIO. My question: http://stackoverflow.com/questions/3867042/one-thread-per-client-doable
Bart van Heukelom