Taking Over Standard Output

As I was running Java process from .NET program, occassionaly I would notice that program would got stuck. Long story short, I traced my issue to following exception:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
...
at java.awt.AWTEventMulticaster.focusLost(AWTEventMulticaster.java:230)
at java.awt.Component.processFocusEvent(Component.java:6397)
...
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)

This exception is not something that would crash application. If I ran Java program from command prompt, exception would be printed out and program would continue.

What ended up being problem was fact that I was reading standard output from my .NET application only upon application exit. If Java application started printing too much stuff before that point, it would fill up the buffer and wait for somebody to read that data. Since there was nobody reading that data, it would wait indifinetely.

There is really easy way around it. Trick is to consume data as soon as it arrives with help of BeginOutputReadLine and OutputDataReceived handler:

process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += process_DataReceived;

process.Start();
process.BeginOutputReadLine();

if (process.HasExited) {
//do something with collected data
}
private static void process_DataReceived(object sender, DataReceivedEventArgs e) {
//store data somewhere (e.g. global StringBuilder)
}

Leave a Reply

Your email address will not be published. Required fields are marked *