Parallelize a blocking call in Java

I am currently using the below code to run a process and print its output from within my own program. My problem is that I’d like to do more than just print the output. However, since the Process being executed scarcely prints output to the console, the commented line is almost never executed because the readLine() method is blocking.

Process p = Runtime.getRuntime().exec(executablePath);
ProcessWatcher pw = new ProcessWatcher(p);
BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()));
while(!pw.isFinished()) {
    String line = output.readLine();
    if(line != null) {
    // I want to do something in parallel here

My problem would be solved if I could give the readLine() call some sort of timeout, or if I could run it in its own Thread. The latter would be preferred, but the former is acceptable. My primary intention is to keep the code simple.

Is there a nice, simple way to parallelize a blocking call, or will I need to create a new class that implements Runnable just for this?


You can wrap you code with.

new Thread(new Runnable() { public void run() {
///put your code here

You cannot do a non-blocking readLine or one with a timeout. In any case, writing code to handle non-blocking connections is usually 10x more complex. 😉

Leave a Reply

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