*this* 真的是从 Java 代码启动第二个 JVM 的最佳方式吗?

时间:2023-03-03
本文介绍了*this* 真的是从 Java 代码启动第二个 JVM 的最佳方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这是我自己以前的问题的后续行动,我有点不好意思问这个......但无论如何:您将如何以独立于系统的方式从独立的 Java 程序启动第二个 JVM?并且不依赖于例如像 JAVA_HOME 这样的环境变量,因为它可能指向与当前运行的 JRE 不同的 JRE.我想出了以下代码,它确实有效,但感觉有点尴尬:

This is a followup to my own previous question and I'm kind of embarassed to ask this... But anyway: how would you start a second JVM from a standalone Java program in a system-independent way? And without relying on for instance an env variable like JAVA_HOME as that might point to a different JRE than the one that is currently running. I came up with the following code which actually works but feels just a little awkward:

public static void startSecondJVM() throws Exception {
    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, 
                AnotherClassWithMainMethod.class.getName());
    Process process = processBuilder.start();
    process.waitFor();
}

此外,当前正在运行的 JVM 可能已使用第二个 JVM 不知道的其他一些参数(-D、-X...、...)启动.

Also, the currently running JVM might have been started with some other parameters (-D, -X..., ...) that the second JVM would not know about.

推荐答案

我不清楚你是否总是希望使用完全相同的参数、类路径或其他任何东西(尤其是 -X 类型的东西 - 例如,为什么要启动辅助进程时,子进程需要与其父进程相同的堆设置.

It's not clear to me that you would always want to use exactly the same parameters, classpath or whatever (especially -X kind of stuff - for example, why would the child need the same heap settings as its parents) when starting a secondary process.

我更愿意使用某种外部配置来为孩子定义这些属性.这需要更多的工作,但我认为最终你将需要灵活性.

I would prefer to use an external configuration of some sort to define these properties for the children. It's a bit more work, but I think in the end you will need the flexibility.

要查看可能的配置设置范围,您可以查看 Eclipse 中的运行配置"设置.那里有相当多的选项卡值得配置.

To see the extent of possible configuration settings you might look at thye "Run Configurations" settings in Eclipse. Quite a few tabs worth of configuration there.

这篇关于*this* 真的是从 Java 代码启动第二个 JVM 的最佳方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:致命异常:java.lang.IllegalStateException - 无法为 LinearLayout 创建层( 下一篇:单例 Bean 如何服务并发请求?

相关文章