views:

347

answers:

5

Hi,

I'd want to restrict the maximum heap size for a Java application but it doesn't seem to work. I'm running the application from a jar package through bat in Windows. Bat contents:

@Echo off
set CLASSPATH=.
java -Xmx32m -classpath %CLASSPATH% -jar MyApplication.jar

This should restrict the maximum heap size of 32 megabytes. However, when I do things consuming memory with the application, the Windows Task Manager shows that the memory consumption goes at least to about 70 megabytes... I even tried with -Xmx2m but that didn't make any difference.

So, I'm not totally sure what's the problem. There is of course stack etc contained in the memory usage but the memory used by the program should be mostly heap space...

Java version seems to be 1.6.0_14.

For those interested what I'm after, I'm trying to see how my application would behave with certain functions when it runs out of heap space.

EDIT: Hmm.. I was surprised that the heap usage was limited to the 32M actually when monitoring with JConsole. Gotta get more memory used...

Thanks for ideas, Touko

+4  A: 

I don't think TaskManager shows Heap Memory specifically. It includes all memory the program is using at that moment.

For analyzing heap memory, you could use a profiler (like Yourkit) and see whether the heap limit -Xmx is obeyed or not. This will also help you analyze the parts of program you are interested in.

Aviator
Yep, I checked console and the heap limit was indeed obeyed, the difference between heap space and other memory usage was just different I expected. With 20M I did succeed to get .OutOfMemoryError: Java heap space
Touko
+3  A: 

Ummm...it doesn't exactly work that way.

While there is a relationship between -Xmx32m and what you see in the task manager, it is not one-to-one. Understand that the Task Manager is not reporting your heap size, but all memory consumed by the JVM, of which your code is only a subset.

Stu Thompson
Yep, in theory I knew that, I only didn't expect the difference to be so big.
Touko
It can be huge. I just posted a question on that today...my server JVM is consuming 3x the max heap size!
Stu Thompson
+1  A: 

Try setting -Xmx128 and see if you get an OutOfMemoryError. This should then confirm that it is at least being set.

DaveJohnston
A: 

Maybe you aren't actually using that much memory, but the JVM is by pulling in external libraries and such.

To test this theory you can use the Runtime class to view total memory and used memory.

tster
A: 

You are seeing the sum of heap size & permanent generation. You can adjust perm size with the -XX:MaxPermSize command-line argument. For example, this will set it to 128m.

java -Xmx32m -XX:MaxPermSize=128m ...
Wayne Young
You have forgotten to mention the memory that the JVM consumes. It is not trivial.
Stu Thompson