Home Articles Technical Articles Java Runtime Process consuming resources
|
|
Java Runtime Process consuming resources |
|
|
Written by Samuel
|
|
tisdag, 16 oktober 2007 |
|
Page 1 of 3 If you’re starting multiple Runtime processes in a Java process, make sure to close them properly.
In this article we will illustrate what happens if we don’t close Runtime Processes. Note that the problem described in this article does not appear on all Java configurations. Some Java environments will close the Runtime Process without the explicit solution in this article. (And in my Windows XP I get different results depending on if CMD.EXE or COMMAND.COM is used). The tests described in this article are done in the following Java environments: - RedHat Linux enterprise ver 3
- Sun JDK 1.5.0_08
- Tomcat 5.5.20
And - Windows XP SP2
- Sun JDK 1.5.0_06
- Tomcat 5.5.20
Example codeJava bean used in both examples below: package test; import org.apache.log4j.Logger; public final class RuntimeProcessBean { private static final Logger logger = Logger.getLogger(RuntimeProcessBean.class); String arg = "dir"; private String[] command() { String osName = System.getProperty("os.name" ); String[] cmd = new String[3]; logger.info("Operating System: "+osName); if( osName.equals( "Linux" ) ) { cmd[0] = "sh" ; cmd[1] = "" ; cmd[2] = arg; } else if( osName.equals( "Windows NT" ) ) { cmd[0] = "cmd.exe" ; cmd[1] = "/C" ; cmd[2] = arg; } else if( osName.equals( "Windows 95" ) || osName.equals( "Windows XP" )) { cmd[0] = "command.com" ; cmd[1] = "/C" ; cmd[2] = arg; } return cmd; } public void test() { String [] cmd = command(); Runtime r = Runtime.getRuntime(); Process p = null; int returnCode = -1; try { p = r.exec(cmd); returnCode = p.waitFor(); logger.info("Command succeeded. "+returnCode); } catch (Exception e) { // Make sure we continue even if exception. logger.warn("Something went wrong. Continue anyway!",e); } } }
|
|
Last Updated ( torsdag, 06 december 2007 )
|
|