views:

54

answers:

1

I'm working on a Java program, and it's been over a year since the last time I used Java, so I'm a little rusty. This program uses Runtime.exec() to call other programs to do its dirty work, and needs to parse their output and update its own GUI accordingly in real time while the other programs are working. What's the best way to do this? I'm currently thinking of having my external-program-executor class have its own internal thread that polls the external program's output stream and then raises events when noteworthy things happen, and then implementing my own EventListener interface for my UI classes. I worry however how that will handle the asynchronous nature of the events being fired. Can anyone give any tips on how to protect the listeners from race conditions, and/or a better approach? Thanks.

+2  A: 
  • You don't have to poll for output in the external process. The Process object returned from Runtime.exec(String) has methods for getting the InputStream for both stderr and stdout and the OutputStream for stdin.
  • You can communicate by sending messages over the OutputStream. Simply push your data on the stream.
  • Spawn a Thread that waits on the stdout OutputStream. Everytime there is new data to read, it will read the data and create an event.
  • Dispatch the event using the Event Dispatcher Thread, EDT. It's used by the Swing/AWT GUI too, so no problems there.
  • You can also use events for sending stuff to the stdin. Simply create an EventListener that listens for certain output events. These events are (possibly translated to a different format) onto the OutputStream and can be read by the stdin of the external process.

Good luck.

Pindatjuh
how do I spawn a thread that will wait for data on the stdout stream (I think you mean InputStream there, btw)?
rmeador