Search code examples
javacommand-lineuser-input

Send commands to a command line Java program while it is working


I have a Java program processing a large set of XML files. The process takes several hours to run and sometimes I need to stop. For now I use CTRL-C to kill it, make a note of which file it was working on, and later I remove the data for those files and re-process them.

Is there a way to have Java keep working while waiting for user input on the command line, and furthermore can I have it keep outputting log info to the command prompt while it listens?

I considered having it wait for user input a few seconds between files, but this would add more time to overall processing, and I'm not sure there's a way to timeout user input easily.


Solution

  • You're interested in spawning another thread for your XML processor to run in. Look to the java.util.concurrent library.

    Your main thread can handle user input while the other thread can report to the console. Handling any concurrency issues between the two can be difficult, it's best advised to avoid communicating between the two as much as possible to save yourself headaches.

    You'll end up adding code that looks something like

    Thread xmlProcessorThread = new Thread(yourRunnableXMLProcessor);
    xmlProcessorThread.run();
    

    And adding the runnable interface to your XML processor (hence the name yourRunnableXMLProcessor)