Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java garbage collection starts to work to prevent memory swapping?

As an example lets say that I set the JVM's maximum heap to 4GB. However, once my application reaches about 3GB, the OS starts to swap some memory to disk. At this point there are several objects already out of scope, and instead of requesting more memory the JVM could first garbage collect old objects. In terms of performance it would be better to have garbage-collection run than to do memory swapping. Is the JVM garbage-collection smart about situations like this or is it completely unaware of it? Can we somehow tune the JVM to address this situation?

I know that there's a chance that the garbage-collection will run before we reach the 3GB and therefore we never actually need to swap memory but that doesn't really answer my question.

EDIT: lets assume that my machine has more than 4GB of memory but sometimes there are other applications taking some of that memory leaving me with less than 4GB. I would rather not have to reduce the maximum heapsize given that most of the times I will have the 4GB but I was wondering if the GC would be smart enough in the other situations.

like image 852
Mario Duarte Avatar asked Aug 23 '10 11:08

Mario Duarte


1 Answers

The JVM is blissfully unaware of the underlaying OS memory management. I remember attending a JavaOne session about GC optimization not long ago and the speaker emphasized that you should always ensure that there is plenty of free memory (RAM, not swap) for the JVM to run, as to avoid paging at all costs, so never assign more memory to the JVM than what you have available at a given time in your system. Even more so, because of the way some GC collection algorithms work, it could have a huge performance penalty if the memory blocks they are collecting are paged.

So never give more memory to the JVM than what you have physically available in your system or if you expect memory consumption to increase over time because of some external processes then assign a heap space that will ensure that it will never be paged. And if you can't satisfy these conditions, well then you need more RAM :)

Update: did a little searching in SO and I found this. Here kdgregory argues that paging shouldn't be an issue because of the way GC works, but he is considering paging due to normal conditions, i.e. memory not being touched for a while, which is not your case, because you would be running out of memory and you will definitely start paging. Also, in case you are running some Linux flavor check John Ferminella's answer and his great blog post explaining how to understand and tune the swap in Linux.

like image 70
teto Avatar answered Sep 24 '22 19:09

teto