0

I am starting a number of external processes (using the class Process) from a class in Java that is itself called by a job scheduler on a Linux platform.

My problem is that the job scheduler kills everything as soon as the last process has been called by the main class.

So I am looking for something like a ThreadPoolExecutor/CountDownLatch kind of way to manage these processes and make the main class wait for them to finish before exiting.

If I call process.waitFor() inside my loop, they will be started sequentially, which I don't want.

Do I need to put these processes into Threads and use a real ThreadPoolExecutor or is there a prettier/simpler way?

Myoch
  • 793
  • 1
  • 6
  • 24

1 Answers1

0

Instead of calling process.waitFor() in the same loop where you start the process, call it in a different loop:

List<Process> processes = new ArrayList<>(); 

// Start subprocesses and add them to the process list
for (...) {
    processes.add(processBuilder.start());
}

// Wait for them to complete
for (Process p : processes) {
    p.waitFor();
}
Joni
  • 108,737
  • 14
  • 143
  • 193