What does InputStream.available() do in Java?

前端 未结 3 2099
南旧
南旧 2020-11-29 00:36

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

The doc says:

Re

相关标签:
3条回答
  • 2020-11-29 01:05

    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

    0 讨论(0)
  • 2020-11-29 01:19

    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.

    0 讨论(0)
  • 2020-11-29 01:28

    Consider if you write software VERY BADLY.. and you write an operating system.

    This operating system takes keyboard input amongst other things.

    So you ask your OS to go and get some keyboard input, but there are no keys pressed and none in the buffer. your Whole OS will then HANG DEAD until it gets a keyboard input.

    Contrast this with 'look ahead', you ask if the KB has any characters BEFORE making the call. You get the answer NO, so your OS then goes and does something else.

    That is WHY you should care, now if you then multiply that by every other potentially blocking task, you can see why 'look ahead' is critical.

    Because It also applies to OUTPUT: A memory to a disk-drive interface can also flood data to the disk-drive faster than it can process it. if you do not know the drive buffer is flooded with data, then the task will block until the buffer can accept more data.

    This also highlights the nonsense of 'there are very few useful uses.'

    0 讨论(0)
提交回复
热议问题