Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running java runtime.exec() for multiple process

In my program I do have a list of n items.

I will be iterating the list and initiate a process like this:

Runtime.getRuntime.exec("cmd /C start abc.bat"+listitem() )

I need to maintain a count of 4 processes. Once any one of the process is completed, I need to start the next process , so the process count should be 4.

I am able to initiate 4 process simultaneously, but not sure on how to keep the count of 4. Basically I need some notification once a process is terminated, so I can start the next, any threading is possible.

Any help on how to implement this, can somebody share a snippet on this above requirement?

like image 634
Vigneshwaran Avatar asked Dec 04 '22 09:12

Vigneshwaran


1 Answers

Use an ThreadPoolExecutor of size 4 and a Runnable implementation which starts the Process and then invokes Process.waitFor(). Since the thread pool will be restricted to 4 threads and all 4 threads will start a process and then wait for it, you'll be certain there won't be more than 4 child processes running.

Some sample code to help you along your way:

ExecutorService executor = Executors.newFixedThreadPool(4);

executor.execute(new Runnable() {
    public void run() {
        //use ProcessBuilder here to make the process
        Process p = processBuilder.start();
        p.waitFor();
    }
});
like image 77
Tim Bender Avatar answered Dec 24 '22 23:12

Tim Bender