Wednesday, April 6, 2016

A launcher to run multiple Applications in same JVM instance

Each single java application runs in its own JVM instance.
We launch a java application by "java" command and it creates a separate JVM instance to run this application.
If we want to run separate applications on same JVM instances we can run them in different threads from a common launcher.
In this example, we have a launcher that accepts different application names and run in different threads.

public class Launcher {
  public static void main(String[] args) throws Exception {
    for (int i = 0; i<args.length; i++) {
      final Class clazz = Class.forName(args[i]);
      new Thread(new Runnable() {
        @Override
        public void run() {
           try{
             Method main = clazz.getMethod("main", String[].class);
             main.invoke(null, new Object[]{});
           } catch(Exception e) {
             // improper exception handling - just to keep it simple
           }
        }
      }).start();
    }
  }
}
Calling it like
  java -cp <classpath for all applications!> Launcher com.example.App1 com.example.App2

No comments:

Post a Comment