Is it possible to call a method in a Java application from another JVM?

When I first developed the Java service for Windows using the apache daemon, I used a mode JVMthat I really liked. You specify your class and static \ stop (static) methods. But with Linux, Jsvc is not like the same option. I really would like to know why ?!

In any case, if I am going to use the Linux init system, I try to find a similar way to perform the same behavior that the application should launch in any case, but in order to stop it, I will have to call the method in the class.

My question is: after running jar, how can I use jvm libraries or something else, call a method in my application (which will try to stop my application gracefully ).

Another question is if the application is running and this application has static methods. If I use the command line javato run a method mainin one, if this is an application class, and a method mainthat staticwill call another static method in the class in which I would like to signal a completion signal, which will call in the same JVM?

+5
source share
2 answers

Why not add ShutdownHookto your application?

- , . , . , , finalization-on-exit. , . , , - , exit.

:

public class ShutdownHookDemo {
    public void start() {
        System.out.println("Demo");
        ShutdownHook shutdownHook = new ShutdownHook();
        Runtime.getRuntime().addShutdownHook(shutdownHook);
    }

    public static void main(String[] args) {
        ShutdownHookDemo demo = new ShutdownHookDemo();
        demo.start();
        try {
            System.in.read();
        }
        catch(Exception e) {
        }
    }
}

class ShutdownHook extends Thread {
    public void run() {
        System.out.println("Shutting down");
        //terminate all other stuff for the application before it exits
    }

}

, :

  • . , System.exit() - .
  • . CTRL-C. kill -SIGTERM pid
  • kill -15 pid Unix.

, :

  • SIGKILL Unix-. kill -SIGKILL pid kill -9 pid
  • TerminateProcess Windows.

, :

public class ReflectionDemo {

  public void print(String str, int value) {
    System.out.println(str);
    System.out.println(value);
  }

  public static int getNumber() { return 42; }

  public static void main(String[] args) throws Exception {
    Class<?> clazz = ReflectionDemo.class;//class name goes here
    // static call
    Method getNumber = clazz.getMethod("getNumber");
    int i = (Integer) getNumber.invoke(null /* static */);
    // instance call
    Constructor<?> ctor = clazz.getConstructor();
    Object instance = ctor.newInstance();
    Method print = clazz.getMethod("print", String.class, Integer.TYPE);
    print.invoke(instance, "Hello, World!", i);
  }
}

:

ClassLoader loader = URLClassLoader.newInstance(
    new URL[] { yourURL },
    getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);

:

+8

All Articles