Reputation: 458
If I start a particular process directly from command line, I see it completely starts in 2-3 seconds.
If I start the exact same process with the exact same command from a Java program, it hangs on start unless the parent is destroyed. Why?
With ProcessBuilder:
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(dir));
Process p = pb.start();
With Runtime.exec:
Runtime.getRuntime().exec(cmd, null, new File(dir));
Either way if I do not set the new Process object to null and call the garbage collector right away,the new process takes up to 3 minutes to do the same things it should do in 3 seconds.
Process p = pb.start();
p = null;
Runtime.getRuntime().gc();
Using the code above fixes the issue. Can someone explain me why? I think it's something related to the JVM an process handling but that's just a guess.
The new process uses Hibernate to connect to a MySQL DB, writes logfiles with log4j, reads from a .properties file and connects to a RabbitMQ server.
Thank you,
have a nice day
Upvotes: 3
Views: 288
Reputation: 3519
Maybe your child process needs some input from stdin? So it hangs until the input is provided by p.getOutputStream().write()
Or it can wait until its stdout will be consumed.
Upvotes: 0
Reputation: 7051
Running external programs from Java applications is notoriously tricky to get right.
I recommend using the high quality Apache Commons Exec library.
If you want to avoid adding a dependency in your code, at least look at the Exec library's Java code to see how it creates and runs processes.
Upvotes: 1