Why runtime.exec hangs in Java ?

I had hit with the same problem runtime.exec() hangs when i tried to execute a lengthy batch script in windows. The problem was clearly described in the java docs which i never read😉

“Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.”

The solution was to clear of the buffer so the process wont hit a deadlock. I have a small sample which could make you more clear.

public class ProcessHandler extends Thread {

InputStream inpStr;
String strType;

public ProcessHandler(InputStream inpStr, String strType) {
this.inpStr = inpStr;
this.strType = strType;

public void run() {
try {
InputStreamReader inpStrd = new InputStreamReader(inpStr);
BufferedReader buffRd = new BufferedReader(inpStrd);
String line = null;
while((line = buffRd.readLine()) != null) {
System.out.println(strType + ” —> ” + line);

} catch(Exception e) {

public static void main(String args[])throws Exception {

/* For windows setting to cmd.exe */
String command[] = {“cmd.exe”,”/c”,cmd};

/* executing the command with environments set. */

Process pro = Runtime.getRuntime().exec(cmd);

/* handling the streams so that dead lock situation never occurs.  */
ProcessHandler inputStream =
new ProcessHandler(pro.getInputStream(),”INPUT”);
ProcessHandler errorStream =
new ProcessHandler(pro.getErrorStream(),”ERROR”);

/* start the stream threads */


10 responses to “Why runtime.exec hangs in Java ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: