Search code examples
javaconcurrencybufferedreaderblocking

java.io.InputStreamReader.ready() blocks execution


i have one unexpected problem. in my project i use object of type java.io.bufferedReader to read some data. it contains readLine() method which reads next line of text from the source.

but the problem with this method is that if source is not ready it blocks execution of the thread which called this method until source has something to read.

fortunately, bufferedReader has ready() method which tells me weather source is ready or not, so i can call it once and a while to see weather there is something to read from the source, and if not to continue doing other jobs. it mostly works fine, but today i noticed something strange.

in some rare cases when i call ready() method ready method itself blocks the execution.

so i am surprised since ready() method is designed to return true only if it is absolutely sure read* method would not block.

as pointed out by "erwin" below, the real problem is not in java.io.BufferedReader but in underlying reader.

to construct buffered reader i use java.io.InputStreamReader.

even if i do not create BufferedReader, but just use InputStreamReader directly, if i call ready() method, call to that method blocks.

so, how is possible that ready() method blocks, and how to avoid it?

thank you.


Solution

  • The ready() method in BufferedReader never blocks by itself - you can easily check that in the source code of BufferedReader.

    The only case in which the ready() method of BufferedReader blocks is, if the ready() method in the underlying Reader blocks (the one that you passed into the constructor of BufferedReader). So your question should be changed to "[my real Reader class] read() method blocks execution".

    For instance, if your underlying reader is a PipedReader, there could be an issue because the ready() and the read() methods are both synchronized. If one Thread is blocked for reading from a PipedReader and another thread uses PipedReader.ready() to check if it can read, then the second thread also blocks until the read() on the first thread completes.