Find Process Count in Java

764 views Asked by At

I am able to launch Process with the help of below command and after launching multiple processes I want to control how many processes I want to keep at some point.

For example:

  1. Initiate a Process inside a for loop of range 0 to 50
  2. Pause the for loop once total active processes are 5
  3. Resume for loop once it drop from 5 to 4 or 3 ...

I tried below code, but I am missing something.

public class OpenTerminal {

    public static void main(String[] args) throws Exception {

        int counter = 0;

        for (int i = 0; i < 50; i++) {
            while (counter < 5) {
                if (runTheProc().isAlive()) {
                    counter = counter + 1;
                }else if(!runTheProc().isAlive()) {
                    counter = counter-1;
                }
            }

        }

    }

    private static Process runTheProc() throws Exception {
        return Runtime.getRuntime().exec("cmd /c start cmd.exe /c \"dir && ping localhost\"");
    }
    
}

Also, how to find out how many process are active? So that I can control active processes at a time.

1

There are 1 answers

0
mikhail.sharashin On BEST ANSWER

You can use thread pool with fixed size. For example:

public static void main(String[] args) throws Exception {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 50; i++) {
            threadPool.submit(runTheProc);
        }

}

private static final Runnable runTheProc = () -> {
        Process process;
        try {
            process = Runtime.getRuntime().exec("cmd /c start cmd.exe /c \"dir && ping localhost\"");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        while (process.isAlive()) { }
};