简体   繁体   中英

Dynamically setting maximum heap size for java process

I have a Java program that is launched by a batch file with a line like this:

javaw -Xms64m -Xmx1024m com.acme.MyProgram

However, on some computers the program will not launch and displays the following message:

Could not reserve enough space for object heap. Could not create the Java virtual machine.

The problem seems to be the the maximum size of the memory allocation pool is larger than the computer can handle. Reducing the maximum size of the memory allocation pool from 1024m to 512m seems to resolve the problem.

Is there a way I can determine how much memory is available on the computer ahead of time (from within the batch file) and determine whether to use -Xmx1024m or -Xmx512m in the batch file invocation? Note that this batch file only needs to work on Windows.

Actually the Java VM already does something similar. If you do not specify -Xms or -Xmx , then these values are inferred from the amount of physical memory on the machine. Or at least so says this page .

You could set -Xms to the minimum heap size which makes your application useful, and let Java determine a proper value for -Xmx .

您可以在此页面上查看一些答案: 让JVM根据需要增加内存需求,直至达到VM限制的大小?

If your program functions correctly with a max heap of 512m, I would use that value.

That said I will also check to see if there is a way to do what you're asking as that is an interesting question.

You could execute from your batch file, check the error level on exit and restart at a lower memory if it failed. I'm not sure the error level would work--if it doesn't you could also check how long it took the program to execute... any thing less than 10sec would be a giveaway.

Just a couple comments though--

If you know it doesn't NEED more than 512, you should run a test to ensure that 1024 actually helps. Larger heaps can often make your GC pauses longer and do little else.

If you're pretty sure you'll use a certain amount of ram (say, the heap will easily fill the 512 you are allocating), you should probably set the min to that number. Setting both the min and max to 512 is good if your program allocates a bunch of stuff but is not situational (always uses about the same amount of ram)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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