What does InputStream.available() do in Java?
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?
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.
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, and the channel has none available, a blocking call will wait (or block) until data is available (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