-2
import java.io.*;
import java.util.concurrent.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Callable;
class _TimeOut_ extends PrintIn_Delays {
  public static void main(String[] args)
      throws InterruptedException {
    TimeWait Timeout = new TimeWait();
    String input = Timeout.readLine();
    String input2 = Timeout.readLine();
  }
}
class Reader implements Callable<String>  {
  public String call() throws IOException {
    BufferedReader br = new BufferedReader(
        new InputStreamReader(System.in));
    String input;
    do {
      input = br.readLine();
    }while ("".equals(input));
    return input;
  }
}
class TimeWait extends _TimeOut_ {

  public String readLine() throws InterruptedException {
    ExecutorService ex = Executors.newSingleThreadExecutor();
    String input = null;
    try {        
        try {
            Future<String> result = ex.submit(
            new Reader());
            input = result.get(5, TimeUnit.SECONDS);
        } catch (ExecutionException e) {
          e.getCause().printStackTrace();
        } catch (TimeoutException e){}
    } finally {
      ex.shutdownNow();
    }
    System.out.println(" "+input);
    return input;
  }
}

This will wait for 5 seconds for user input. If user don't enter anything, it displays null. Now the problem is : When I run it, it waits for 5 seconds for my input but I don't enter anything and so output is null. Then in the second input, I enter 'hi'. But it still waits for 5 seconds ( which it shouldn't) and after taking the input, it still displays null. Here is the output :

null 
hi
null
reto
  • 9,995
  • 5
  • 53
  • 52
  • 5
    Please find a better title for your question –  Jun 20 '18 at 06:48
  • 4
    Welcome on Stack Overflow. Please [take the tour](https://stackoverflow.com/tour) and [read the Help Center](https://stackoverflow.com/help) to learn how to ask a good and well-received question. Your title is currently quite terrible and does not explain at all what your problem is. Also please show what your understanding of the problem is, why you think it happens and what you tried to fix it. – Ben Jun 20 '18 at 06:48
  • This was my first question here. Sorry for that. – Aditya Arora Jun 20 '18 at 10:56

1 Answers1

0

The problem is that even though you are stopping waiting for the first Future to get a value, it doesn't stop waiting for a value. The BufferedReader.readLine() call simply blocks, waiting for input, or closure of the input stream, irrespective of the timeout.

So, when you do eventually enter a value, the first thread gets it; then there is nothing for the second thread to read.

(But, of course, the second thread hasn't stopped waiting either: this will continue to wait for input, or closure of the input stream).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243