3

Can I spawn multiple different JVMs given the same Main.class, arguments and VM options? Is it possible to do it with the ProcessBuilder?

4
  • nice question , i am too curious now Commented Dec 11, 2014 at 13:30
  • Me too. I found some sample code here and there but nothing that actually worked :( Commented Dec 11, 2014 at 13:34
  • With "different JVM" do you mean multiple instances of the same JVM installation or a JVM 1.6, JVM 7, JVM 8, etc.? Commented Dec 11, 2014 at 13:46
  • Multiple instances of the same JVM installation. Commented Dec 11, 2014 at 13:51

1 Answer 1

2

Here is a basic example using Process that starts 10 different JVM process:

   for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {

                public void run() {
                    try {
                        //start a new jvm with 256m of memory with the MyClass passing 2 parameters
                        String cmd = "java -Xmx256M -cp myjar.jar com.mymainclass.MyClass par1 par2";
                        Process p = Runtime.getRuntime().exec(cmd);
                        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        String line = br.readLine();
                        while (line != null) {
                            line = br.readLine();
                        }
                        br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                        line = br.readLine();
                        while (line != null) {
                            line = br.readLine();
                        }
                    } catch (IOException e) {
                    }

                }
            }).start();
        }
Sign up to request clarification or add additional context in comments.

3 Comments

So I can't take advantage of the fact that I m doing all this from within the same jar in order not have to reference it this way and copy all environment parameters and arguments?
You probally should use the Apache Commons Exec to prevent common mistakes when executing external processes from Java.
@KaterinaA. the process is a clean new environment, it wont use anything of the current environment... this is the same with you open a prompt and enter de command

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.