Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ProcessBuilder vs Runtime.exec()

Which one is better? By better I mean which one has better security, etc. (not ease of use).

like image 516
JavaIsGreat Avatar asked May 04 '11 16:05

JavaIsGreat


People also ask

Is ProcessBuilder thread safe?

ProcessBuilder is not thread safe, as stated in the javadoc.

What is ProcessBuilder in Java?

This class is used to create operating system processes. Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes.

What is exec method in Java?

exec(String command) method executes the specified string command in a separate process. This is a convenience method. An invocation of the form exec(command) behaves in exactly the same way as the invocation exec(command, null, null).

How do I stop a ProcessBuilder in Java?

You can call destroy() method on it.


1 Answers

Ease of use is the only real difference between those two.

Note that ease of use can lead to security by helping to avoid mis-use.

At least on OpenJDK 6 Runtime.exec() is implemented using ProcessBuilder:

public Process exec(String[] cmdarray, String[] envp, File dir)
    throws IOException {
    return new ProcessBuilder(cmdarray)
        .environment(envp)
        .directory(dir)
        .start();
}
like image 189
Joachim Sauer Avatar answered Oct 07 '22 01:10

Joachim Sauer