2

I've a console Java application, which does some tasks in the background. Java doesn't support console kbhit() for testing if there is something in keyboard buffer and as I know all console reads and tests are blocking.

What I'm going to do is to start a background thread with something like console.readLine() and then put some termination flag after this blocking call is finished. Application background tasks will check this flag and decide whether they need to terminate.

BTW, my application is going write to console during its work (logging via logback and such), but never read it.

Is such strategy a good one?

Vladislav Rastrusny
  • 29,378
  • 23
  • 95
  • 156
  • to me, dedicating a thread to `console.readLine()` sounds like a good approach...have you tested it? the only thing you'll need to worry about is synchronizing on the flag. – mre May 15 '11 at 00:42
  • @sthupahsmaht Which flag? Console is already synchronized in Java – Vladislav Rastrusny May 15 '11 at 09:19
  • and I quote, "What I'm going to do is to start a background thread with something like console.readLine() and then put some termination flag after this blocking call is finished. Application background tasks will check this flag and decide whether they need to terminate." – mre May 15 '11 at 14:28
  • @sthupahsmaht Ah, well, but what's the point synchronizing it, if it is written by only one thread (the one that waits for console input)? All others will just read it. – Vladislav Rastrusny May 15 '11 at 15:21
  • at least declare it `volatile`, otherwise you run the risk of never seeing the new value. – mre May 15 '11 at 22:25

1 Answers1

1

you can use System.in.available()>0 but that only buffers full lines (after pressing the enter key) from the console

ratchet freak
  • 47,288
  • 5
  • 68
  • 106