0

I got this question from Head First Java by Kathy Sierra and Bert Bates. In the Networking and Threads section of the book, they built a chat client and handled incoming messages by starting a separate thread:

public class IncomingReader implements Runnable {
    public void run() {
        String message;
        try {
            while ((message = reader.readLine()) != null) { //reader is a BufferedReader from an InputStreamReader of a Socket
                System.out.println("read " + message);
                incoming.append(message + "\n"); //incoming is a JTextArea they declared earlier
            }
        } catch (Exception ex) {ex.printStackTrace();}
    }}  

And this thread is started only once, after they setup the Swing GUI and the readers and writers.

So my question is, how is this thread able to stay alive and keep listening for incoming messages. Shouldn't it go past the while loop and die when message is null?

liueri19
  • 13
  • 3
  • 3
    `BufferedReader.readLine()` is blocking, it will wait until there is something to read. See [this](http://stackoverflow.com/questions/15521352/bufferedreader-readline-blocks) – BackSlash Oct 29 '16 at 18:34
  • Unclear what `reader` is, but from your description, it's a Socket's input stream that is never closed – OneCricketeer Oct 29 '16 at 18:37
  • 1
    @BackSlash Very helpful link. Could you word your comment as an answer so I can accept it? – liueri19 Oct 29 '16 at 18:54

1 Answers1

0

BufferedReader will keep on reading the input until it reaches the end. But if there is nothing to read, then it will keep looping or wait until there is input.

BufferedReader readLine() blocks

Community
  • 1
  • 1