Tuesday, October 18, 2011

Process hangs in java

The correct solution according to my experience is the getErrorStream and getOutputStream
of the Process must be executed concurrently in a separate Thread

When you run a  Process proc

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);

You need to empty errorStream and outputStream in a separate Thread concurrently.
In case if you get the outputStream  first and get ErrorStream  afterwards it may lead to the Process hang or vice versa.

To make the  empty the errorStream and outputStream in a separate Thread you can use StreamGobbler as follows:


class StreamGobbler extends Thread
{
    InputStream is;
    String type;
    String command;
    StreamGobbler(InputStream is, String type)
   {
        this.is = is;
        this.type = type;
    }

   public void run()
      {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
           {
                 System.out.println(type + ">" + line);  //Stream to the STDOUT
            }{
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
               {
                System.out.println(type + ">" + line);
                area1.append(line);
              }
            } catch (IOException ioe)
              {
                ioe.printStackTrace();
               }
       }

     public static void main(String args[])
    {
                    Runtime rt = Runtime.getRuntime();
                    Process proc = rt.exec(command);
                    // error message
                    StreamGobbler errorGobbler = new
                        StreamGobbler(proc.getErrorStream(), "ERROR");          
                    //  output  message
                    StreamGobbler outputGobbler = new
                        StreamGobbler(proc.getInputStream(), "OUTPUT");

                    //Start the ErrorStream and inputStream in separate Threads
                    errorGobbler.start();
                    outputGobbler.start();

     }

ANd in case you are using a GUI for displaying the message you need to
use SwingWorker Thread .This i will cover in another blog.

No comments:

Post a Comment