Wed 4 Jan 2012
A Byte Sized Primer on JVM Memory Management
The Java VM automatically manages allocation and deallocation of memory during program execution. The Garbage Collector (GC) is responsible for scanning the heap and freeing up space occupied by unreachable objects. In some ways, automatic memory management makes programming way simpler and less error prone.
Sweet! Memory is managed automatically so I don’t need to care about it!
Nope, not necessarily. If you understand just a little about memory management you can tune your application to help the JVM do its job more efficiently. So let’s learn a little background here and in a later post I’ll write about tweaking your code.
The JVM splits memory up into sections:

It turns out that the majority of Java objects are very short-lived: new‘d up in a block, used, and destroyed. These objects are created in the Eden space and they are GC’d by a serial process which runs with minimal impact on the application.
Key point: GC in the Eden space is a relatively lightweight operation so we prefer this to happen.
Objects in the Eden space that are not culled by the GC are copied into the Survivor space. And occasionally, the runtime copies longer-lived objects from the short-term area into the Tenured space.
When Tenured fills up the the JVM performs a major mark-and-sweep GC which will stop all threads whilst it clears up, reorganizes and compresses this space.
This “stop-the-world” GC can cause your application to hang and the user will see a blank screen or spinning beach ball of doom. ![]()
Worse, your application can GC Storm. This happens where the tenured space is pretty much always full so the collector runs frequently. Yes, I’m talking about you IntelliJ.
So, what can you watch for? How about: premature object creation, holding references to objects you don’t need, String concatenation operations, statics, not closing JDBC Statements/ResultSets in a finally block…
Finally, measure don’t guess: understand your application’s memory profile, use a profiler like JMeter, and a Memory Analyzer Tool to have fun with heap dump analysis.
