Java 在运行时设置 JVM 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1754077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:19:03  来源:igfitidea点击:

Setting JVM parameters at runtime

javajvmikvm

提问by Guy

Is it possible to change/modify/adding VM parameters after the JVM is already loaded (running)? If so, how can I do it?

JVM 已加载(运行)后是否可以更改/修改/添加 VM 参数?如果是这样,我该怎么做?

采纳答案by Harold L

For properties you'd set via the -Dflag on the command line, you want System.setProperty. For example:

对于您通过-D命令行上的标志设置的属性,您需要System.setProperty。例如:

System.setProperty("propname", "hello world");

// ... later ...
String value = System.getProperty("propname");

Update:

更新:

You can't enable debugging dynamically, but you can enable debugging at startup but attach a debugger later. With the following, you can listen on port 12345 and start your program running right away (via suspend=n). Then you can attach a debugger if/when you need to, detach the debugger, attach again later, etc.

您不能动态启用调试,但可以在启动时启用调试,但稍后附加调试器。使用以下命令,您可以侦听端口 12345 并立即启动程序运行(通过suspend=n)。然后,您可以在需要时附加调试器、分离调试器、稍后再次附加等。

-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=12345

Of course, this hurts performance even when the debugger isn't attached, so it only works well in dev/test code, not production. For that, you want logging, e.g. log4j.

当然,即使没有附加调试器,这也会损害性能,因此它仅适用于开发/测试代码,而不适用于生产。为此,您需要日志记录,例如log4j

回答by mP.

A short answer is that you cannot change VM parameters at runtime. The Runtime class does expose some options such max memory. The main parameters such as max memory should only be set by an admin type allowing management of resources when multiple JVMs co exist on a machine. Allowing one JVM to get greedy and ask for lots and lots more than it was allocated would kill this constraint.

简短的回答是您不能在运行时更改 VM 参数。Runtime 类确实公开了一些选项,例如最大内存。主要参数(如最大内存)应仅由允许管理资源的管理员类型设置,当多个 JVM 共存于一台机器上时。允许一个 JVM 变得贪婪并要求比分配的更多很多会消除这种约束。