6

Is there a way to make BufferedReader.readLine() not hang?

I'm creating a server that:

  • Checks if the client has delivered any input.
  • If not, it executes other code and eventually loops back to checking the client for input.

How can I check if the client has delivered any input without running readLine()? If I run readLine(), the thread will hang until input is delivered?

Cin316
  • 651
  • 1
  • 9
  • 19
  • 2
    Why? The server should have a separate reading thread per client if you're using blocking I/O. – user207421 Mar 19 '13 at 21:48
  • I don't want to have to create two threads for each user. I already have one thread for each user. – Cin316 Mar 19 '13 at 22:06
  • 1
    This is the unfortunate reality of Java's I/O library. You can either 1) Spin up separate threads for reading 2) Use the NIO library 3) Don't use readLine() and do your own buffering and end-of-line management yourself – creechy Mar 19 '13 at 22:22

1 Answers1

8

You can use BufferedReader.ready(), like this:

BufferedReader b = new BufferedReader(); //Initialize your BufferedReader in the way you have been doing before, not like this.

if(b.ready()){
    String input = b.readLine();
}

ready() will return true if the source of the input has not put anything into the stream that has not been read.

Edit: Just a note, ready will return true whenever even only one character is present. You can use read() to check if there is a line feed or carriage return, and those would indicate an end of line.

For more info: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#ready()

Cin316
  • 651
  • 1
  • 9
  • 19
  • 7
    Doesn't this only guarantee that the next call to `read()` doesn't block? The link says nothing about `readLine()`. – Keppil Mar 19 '13 at 21:45
  • 3
    Even if it is ready, that only means that there is at least one byte, not necessarily a whole line. This won't necessarily work in all cases, though you may get lucky and it will work for what you are doing. – TofuBeer Mar 19 '13 at 22:45