Monday, March 18, 2013

java.lang.Runtime.getRuntime().exec leaking pipes

I do this in a WebApp in Tomcat:
Process proc = java.lang.Runtime.getRuntime().exec("generateSQLDeveloperConnections.sh");
proc.waitFor();


but apparently according to this post: http://mark.koli.ch/2011/01/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec.html this can leak resources.

To investigate, I run the PRICELESS lsof on the Tomcat pid 12193:

/usr/sbin/lsof -a -p 12193

and I notice after each run of getRuntime().exec 3 extra pipes:

java    12193  soa   76w  FIFO      0,6      0t0 14925870 pipe
java    12193  soa   77r  FIFO      0,6      0t0 14925871 pipe
java    12193  soa   79r  FIFO      0,6      0t0 14925872 pipe


who are never closed.

I will definitely add the code

import static org.apache.commons.io.IOUtils.closeQuietly;

Process p = null;
try {
  p = Runtime.getRuntime().exec(...);
  // Do something with p.
} finally {
  if(p != null) {
    closeQuietly(p.getOutputStream());
    closeQuietly(p.getInputStream());
    closeQuietly(p.getErrorStream());
  }
}

and see if this takes care of the issue.

No comments: