简体   繁体   English

如何在现有JVM中运行程序?

[英]How to run a program inside an existing JVM?

I have a JVM which is already running. 我有一个已经运行的JVM。 I have its processID with me. 我有它的processID。 Now I wish to run some other Java code inside this JVM,ie, the code should run in this existing JVM rather than spinning up its own JVM. 现在我希望在这个JVM中运行一些其他Java代码,即代码应该在这个现有的JVM中运行,而不是在自己的JVM上运行。

I have already looked at the Attach API . 我已经看过Attach API了 However it requires code to be packaged in a JAR. 但是,它需要将代码打包在JAR中。

Is there any other way? 还有其他方法吗?

The easiest way seems to be with the Attach API. 最简单的方法似乎是使用Attach API。 However since you don't want to use it, you might want to google about RMI/JMS/JMX which would also allow you to do similard manipulation. 但是,由于您不想使用它,您可能需要谷歌关于RMI / JMS / JMX,这也允许您进行类似的操作。

If you start the program using the standard java command, then a new VM will be created for each program. 如果使用标准java命令启动程序,则将为每个程序创建一个新VM。

However, since this look like an XY problems, here an easier alternative that would probably allow you to do what you want. 但是,由于这看起来像XY问题,这里有一个更容易的选择,可能会让你做你想要的。

It is possible to run programs on different threads of the VM. 可以在VM的不同线程上运行程序。

Here an interesting snippet that would create a simple launcher, then you can start the program giving the main class of each program you want to start as argument to the main method which will create a new thread for each program, but everything will be running on the same VM as the launcher. 这里有一个有趣的片段,可以创建一个简单的启动器,然后你可以启动程序,给你想要作为main方法的参数启动的每个程序的主类,它将为每个程序创建一个新线程,但一切都将在与启动器相同的VM。

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();
    }
  }
}

Note : I don't know what you are really trying to do, but if it is to be used with big applications, you might want to increase the heap properties to avoid problems. 注意:我不知道您真正想要做什么,但如果它要与大型应用程序一起使用,您可能希望增加堆属性以避免出现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM