1

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.

Roman C
  • 47,329
  • 33
  • 60
  • 147
FaultyJuggler
  • 448
  • 1
  • 7
  • 23
  • You should see also see this: http://stackoverflow.com/questions/11521597/java-console-application-main-thread-spawns-a-key-listener-thread – Boris Pavlovic Nov 28 '12 at 22:53

2 Answers2

1

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)

MushinNoShin
  • 4,105
  • 2
  • 28
  • 45
  • Is this how larger scale projects like jboss and hadoop do this? That is they run large processes in the background but have a command line shell interface you can connect to. – FaultyJuggler Nov 29 '12 at 21:05
  • They work in a similar fashion yes but to say they work the way I'm suggesting may be an oversimplification. Normally there is some message passing between the two, how that is handled in a problem unto itself. http://en.wikipedia.org/wiki/Message_passing might give you some added background. Once again, the `java.util.concurrent` library will give you the tools you need. – MushinNoShin Nov 30 '12 at 02:35
0

In your command line application start a new thread that actually does the work of processing files. The processing thread could check an internal flag after each file and determine whether to continue or not. The main application thread would continue to listen for command line input and could set the value of the flag based on when it receives input.

digitaljoel
  • 25,150
  • 14
  • 83
  • 114