ProcessBuilder - Start Another Process / JVM - HowTo?

I am writing a network application where each client has a Singleton ClientManager. For testing, I would like to create several clients (each in its own VM / process) without manually starting the program n times.

The following two stackoverflow questions already describe how to do this:

My code is based on them, but it does not work:

  • The main program will not continue after calling spawn.
  • Generated code does not start.

Here is the full code using ProcessBuilder :

public class NewVM {
  static class HelloWorld2 {
    public static void main(String[] args) {
      System.out.println("Hello World");
      System.err.println("Hello World 2");
    }
  }
  public static void main(String[] args) throws Exception {
    startSecondJVM(HelloWorld2.class, true);
    startSecondJVM(HelloWorld2.class, false);
    System.out.println("Main");
  }
  public static void startSecondJVM(Class<? extends Object> clazz, boolean redirectStream) throws Exception {
    System.out.println(clazz.getCanonicalName());
    String separator = System.getProperty("file.separator");
    String classpath = System.getProperty("java.class.path");
    String path = System.getProperty("java.home")
            + separator + "bin" + separator + "java";
    ProcessBuilder processBuilder = 
            new ProcessBuilder(path, "-cp", 
            classpath, 
            clazz.getCanonicalName());
    processBuilder.redirectErrorStream(redirectStream);
    Process process = processBuilder.start();
    process.waitFor();
    System.out.println("Fin");
  }
}

What am I doing wrong?

Btw:

  • I am using Eclipse.
  • Singleton's problem is a simplified example. Do not suggest creating a factory.

: HelloWorld2 .

+3
2

HelloWorld2 . , java .

, .

class Main
{
    static class Main2
    {
        public static void main ( String [ ] args )
        {
            System . out . println ( "YES!!!!!!!!!!!" ) ;
        }
    }

    public static void main ( String [ ] args )
    {
        System . out . println ( Main2 . class . getCanonicalName ( ) ) ;
        System . out . println ( Main2 . class . getName ( ) ) ;
    }
}

class Main3
{
    public static void main ( String [ ] args )
    {
        System . out . println ( "YES!!!!!!!!!!!" ) ;
    }
}
  • getCanonicalName getName . ? .
  • Main3.
+2

, : process.waitFor() main() .

, , ProcessBuilder , JVM . , static void main(String[]).

+1

All Articles