Starting a new JVM in java

Some times it is necessary to start a java class in another JVM, because you want to do some special configuration stuff, library update or what ever. An easy and nice to handle way is to use the api of Apache Ant.

At first we need a small example class we want to launch:

public class MyClassToLaunch {
   public static void main(String[] args) {
      if(args.length > 0) {
         System.out.print("args: ");
         for(int i=0; i<args.length; i++)
            System.out.print(args[i]+", ");
         System.out.println();
      }
      for(int i=0; i<10; i++) {
         System.out.print('.');
         try {
            Thread.sleep(500);
         } catch (InterruptedException e) {
         }
      }
   }
}

Now let’s have a look at the launcher class:

/**
 * LGPL
 */
public class MyLauncher {
   public static void main(String[] args) {
      // global ant project settings
      Project project = new Project();
      project.setBaseDir(new File(System.getProperty("user.dir")));
      project.init();
      DefaultLogger logger = new DefaultLogger();
      project.addBuildListener(logger);
      logger.setOutputPrintStream(System.out);
      logger.setErrorPrintStream(System.err);
      logger.setMessageOutputLevel(Project.MSG_INFO);
      System.setOut(new PrintStream(new DemuxOutputStream(project, false)));
      System.setErr(new PrintStream(new DemuxOutputStream(project, true)));
      project.fireBuildStarted();

      Throwable caught = null;
      try {
         // an echo example
         Echo echo = new Echo();
         echo.setTaskName("Echo");
         echo.setProject(project);
         echo.init();
         echo.setMessage("Launching ...");
         echo.execute();

         /** initialize an java task **/
         Java javaTask = new Java();
         javaTask.setNewenvironment(true);
         javaTask.setTaskName("runjava");
         javaTask.setProject(project);
         javaTask.setFork(true);
         javaTask.setFailonerror(true);
         javaTask.setClassname(MyClassToLaunch.class.getName());

         // add some vm args
         Argument jvmArgs = javaTask.createJvmarg();
         jvmArgs.setLine("-Xms512m -Xmx512m");

         // added some args for to class to launch
         Argument taskArgs = javaTask.createArg();
         taskArgs.setLine("bla path=/tmp/");

         /** set the class path */
         Path classPath = new Path(project);
         File classDir = new File(System.getProperty("user.dir"), "classes");
         javaTask.setClasspath(classPath);
         Path classPath = new Path(project);
         classPath.setPath(classDir.getPath());
         FileSet fileSet = new FileSet();
         fileSet.setDir(classDir);
         fileSet.setIncludes("**/*.jar");
         classPath.addFileset(fileSet);
         javaTask.setClasspath(classPath);

        javaTask.init();
        int ret = javaTask.executeJava();
        System.out.println("return code: " + ret);

      } catch (BuildException e) {
         caught = e;
      }
      project.log("finished");
      project.fireBuildFinished(caught);
   }
}

If you know ant, you recognize the typically structure of an ant task. A really cool feature is the logging stuff.
Now you have the possibility to do all the complex jvm calls you need.

, ,

  1. #1 by balchot on 2012/08/29 - 15:51

    Very very great post! Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: