1

So I'm trying to make a console app that imposes a time limit to user. User is expected to enter a certain number, but after a certain amount of milis (10 secs), it will break out of that input mode and tell user that time has expired and program moves on. This is my code:

    final InputStreamReader isr = new InputStreamReader(System.in);
    final BufferedReader br = new BufferedReader(isr);

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            try {
                System.in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    new Timer().schedule(task, 10000);

    try {
        String line = br.readLine();
        if (line == null) {
            System.out.println("TIME EXPIRED");
        } else {
            System.out.println("TEXT: " + line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("END");

It seems to work properly, except that the program seems to be stuck at the input mode indefinitely. It spits out "END" to the console, but the program doesn't terminate. It seems it's still expecting input from user. What did I do wrong? Or is there a better way to do this?

garbagecollector
  • 3,731
  • 5
  • 32
  • 44
  • It has been asked and answered: http://stackoverflow.com/questions/804951/is-it-possible-to-read-from-a-java-inputstream-with-a-timeout – Eugene Retunsky Apr 02 '12 at 20:43
  • Have you tried to dump the thread stacks? `kill -QUIT` or jconsole may show you them. As @evanwong points out, you are not stuck where you think you are. You can see what user threads are not daemon which may be the issue. – Gray Apr 02 '12 at 21:29

1 Answers1

1

Timer is not a daemon thread, it won't terminate itself unless you call timer.cancel() or create the timer in this way:

new Timer(true).schedule(task, 10000);
evanwong
  • 5,054
  • 3
  • 31
  • 44