Spawning New Processes From a Java Program

Spawning New Processes From a Java Program

The Java Runtime Environment (JRE) shields Java developers from the system level burdens of starting and stopping processes. A Java application runs inside the JVM, while a Java applet runs in a Web browser. In effect, both run inside the JVM (since the browser runs the applet in its own JVM). A standard Java application handles parallel tasks by running these tasks in independent threads.

However, most systems that support a Java runtime environment are capable of running several processes simultaneously. Java applications also are able to start new system programs calling the exec() method of the Runtime class. The exec() method has four forms:

 1. public Process exec(String cmd) throws IOException2. public Process exec(String[] cmds) throws IOException3. public Process exec(String cmd, String[] env) throws IOException4. public Process exec(String[] cmds, String[] env) throws IOException

The cmd parameter in Line 1 specifies the process to run. In Line 2, an array of String variables, cmds, is passed to the exec() method. The first String (cmd[0]) is the program name and the rest of the array strings are the arguments to the program. Lines 3 and 4 extend the methods in Lines 1 and 2 by allowing the Java program to supply environment variables in the array env.

Note that the exec() method results in the creation of a new child process. This process is a system process managed by the platform’s operating system that runs outside the JVM. The following example uses the exec() call shown on Line 4:

 1. Runtime rt = Runtime.getRuntime();2. String[] cmds = { "/bin/ls", "/" };3. String[] env = { "TERM=VT100" };4. Process p1 = rt.exec(cmds, env);

This code is equivalent to running the shell commands:

 $ set TERM=VT100$ /bin/ls /
See also  How to Avoid Money Transfer Scams  

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist