0

Once user entered data timer stops and BuferredReader closed. If 10 seconds passed and no input - BuferredReader closed and user unable to make input. Below code works, but not 100% correct. Please suggest any solution.

public class Main  {

public static void main(String[] args) throws IOException {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    NewThread nt = new NewThread(br);
    Thread newThread = new Thread(nt);
    newThread.start();


    System.out.print("Please enter data: ");
    System.out.println("");

     String value = br.readLine();
    System.out.println(value);
    nt.shutdown();
}
}

class NewThread implements Runnable {

volatile BufferedReader br;
 volatile boolean running ;

 public NewThread(BufferedReader br) throws IOException {
     this.br = br;
     this.running = br.ready();
 }
 @Override
 public void run() {
     int count = 10;
     try {
     while (!running) {
         System.out.print("("+count +")"+ '\r');
         Thread.sleep(1000);
         count--;
         if (count <0){
             shutdown();
         }
     }
         } catch (InterruptedException | IOException e) {
             e.printStackTrace();
         }
 }
 public void shutdown () throws IOException {
     running=true;
     br.close();
 }

 }
Ilja Veselov
  • 69
  • 1
  • 8

1 Answers1

0

So, firsty you calling method:

br.readLine()

BufferedReader implementation of this method uses synchornized block when waiting for user input. Below I put part of code this method:

String readLine(boolean ignoreLF) throws IOException {
    StringBuffer s = null;
    int startChar;

    synchronized (lock) {
        ensureOpen();
...}

Nextly, when you call method shutdown from NewThread(after time out) on your reader, which call close method on buffer - execution of this metod uses synchronized mechanism too:

public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
            return;
        try {
            in.close();
        } finally {
            in = null;
            cb = null;
        }
    }
}

so it means that close method will be executed after finished readLine method (exactly after execution synchronized block in readLine method), which is finished when you pass parameter to console. I suppose that is not possible to close this reader after calling readLine method by standard java mechanism when you use System.in.

piterpti
  • 11
  • 3