javaconsolekbhit

Is separate thread a good strategy to terminate application with background tasks by keypress?


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?


Solution

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