set timeout for user's input

A slightly easier way to do this than Benjamin Cox's answer would be to do something like

int x = 2; // wait 2 seconds at most

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
long startTime = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime) < x * 1000
        && !in.ready()) {
}

if (in.ready()) {
    System.out.println("You entered: " + in.readLine());
} else {
    System.out.println("You did not enter data");
}

This will, however consume more resources than his solution.


Not right out of the box, no. Normally the Reader only breaks out of a read() call when another thread closes the underlying stream, or you reach the end of the input.

Since read() is not all that interruptible this becomes a bit of a concurrent programming problem. The thread that knows about the timeout will need to be able to interrupt the thread that's trying to read the input.

Essentially, the reading thread will have to poll the Reader's ready() method, rather than getting locked in read() when there's nothing to read. If you wrap this polling and waiting operation in a java.util.concurrent.Future, then you call the Future's get() method with a timeout.

This article goes into some detail: http://www.javaspecialists.eu/archive/Issue153.html

Tags:

Java