Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of specifiying memory limit of Java Virtual Machine?

Tags:

java

jvm

I have set the default memory limit of Java Virtual Machine while running Java Application like this...

java -mx128m ClassName

I Know this will set maximum memory allocation pool to 128MB, but I don't know what the benefit is, of specifying this memory limit of JVM?

Please enlighten me in this issue...

like image 351
Saravanan Avatar asked Sep 14 '11 07:09

Saravanan


2 Answers

On Sun's 1.6 JVM, on a server-class machine (meaning one with 2 CPUs and at least 2GB of physical memory) the default maximum heap size is the smaller of 1/4th of the physical memory or 1GB. Using -Xmx lets you change that.

Why would you want to limit the amount of memory Java uses? Two reasons.

Firstly, Java's automatic memory management tends to grab as much memory from the operating system as possible, and then manage it for the benefit of the program. If you are running other programs on the same machine as your Java program, then it will grab more than its fair share of memory, putting pressure on them. If you are running multiple copies of your Java program, they will compete with each other, and you may end up with some instances being starved of memory. Putting a cap on the heap size lets you manage this - if you have 32 GB of RAM, and are running four processes, you can limit each heap to about 8 GB (a bit less would be better), and be confident they will all get the right amount of memory.

Secondly (another aspect of the first, really), if a process grabs more memory than the operating system can supply from physical memory, it uses virtual memory, which gets paged out to disk. This is very slow. Java can reduce its memory usage by making its garbage collector work harder. This is also slow - but not as slow as going to disk. So, you can limit the heap size to avoid the Java process being paged, and so improve performance.

like image 193
Tom Anderson Avatar answered Oct 21 '22 10:10

Tom Anderson


There will be a default heap size limit defined for the JVM. This setting lets you override it, usually so that you can specify that you want more memory to be allocated to the java process.

like image 35
krock Avatar answered Oct 21 '22 12:10

krock