Java: how to abort a thread reading from System.in

pts picture pts · May 15, 2011 · Viewed 9.9k times · Source

I have a Java thread:

class MyThread extends Thread {
  @Override
  public void run() {
    BufferedReader stdin =
        new BufferedReader(new InputStreamReader(System.in));
    String msg;
    try {
      while ((msg = stdin.readLine()) != null) {
        System.out.println("Got: " + msg);
      }
      System.out.println("Aborted.");
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

}

In another thread, how do I abort the stdin.readline() call in this thread, so that this thread prints Aborted.? I have tried System.in.close(), but that doesn't make any difference, stdin.readline() is still blocking.

I'm interested in solutions without

  • busy waiting (because that burns 100% CPU);
  • sleeping (because then the program doesn't respond instantly to System.in).

Answer

McDowell picture McDowell · May 15, 2011

Heinz Kabutz's newsletter shows how to abort System.in reads using a buffer and ExecutorService.

Now, I don't know whether this approach leaks, isn't portable or has any non-obvious side-effects. Personally, I would be reluctant to use it.

You might be able to do something with NIO channels and file descriptors - my own experiments with them didn't yield any results.