views:

322

answers:

4

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.

A: 

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.

Chris B.
A: 

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)

Bill K
+5  A: 

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.

Thomas Pornin
I've confirmed with Sun's Java 6 it does set `-Xmx` to about 1/4 physical memory (that page was for Java 5 and says it should have been limited to 1GB but with 6GB RAM I get -Xmx1365m so the limit may have been removed or increased with Java 6).
Kevin Brock
+1  A: 

You could take a look at this page for some answers: http://stackoverflow.com/questions/1152507/get-jvm-to-grow-memory-demand-as-needed-up-to-size-of-vm-limit/1158892#1158892

Peter Smith