Main Content

Java - Memory Allocation and garbage collection

Archive - Originally posted on "The Horse's Mouth" - 2009-03-14 11:28:06 - Graham Ellis

When you're running a dynamic application (and most of the languages we teach these days are dynamic), memory is allocated and released as necessary at run time, with allocation happening 'as required' and being released from time to time by a garbage collector - there is no point is collecting a few bytes of memory every time that there is some released as that would be very inefficient - rather like calling out your local council to collect your rubbish every time you finished a packet of crisps. So if you look at a graph of memory usage, you'll see a saw-toothed shape like this:

In Java, data (objects) are held in memory in different areas, and moved around between them, to make the memory management and garbage collection more efficient, and the memory areas each have their own names.

New objects are allocated memory in the Eden Space memory pool (as in created in Eden) and by the nature of most applications in which the majority of objects only survive for a short while, that's where they remain for their short lives. Here is a graph showing the size of Eden Space alone - you'll notice the same general saw toothed shape, but the curve drops virtually to zero at the base of every tooth:


At minor garbage collection time, objects which survive garbage collection are moved to the Survivor Space which, as the name implies, is used for objects that have a longer life span / expectancy. Here's a graph of survivor space - you'll see some gentle ups and downs but in general a much smoother curve!


And that minority of objects that aren't going to be going away but are 'around for the duration' become a part of the Tenure space. I wouldn't describe the graph for tenure as a curve - more like a straight line!


All four sample graphs are taken from jconsole, monitoring a Tomcat server that's ticking over with just a few test connections / pages being served.

There are also other memory pools used and shown by jconsole - there's the code cache where the code that's being run - both Tomcat itself and the classes it is running - resides, and you have permanent areas too - one "rw" (read / write) and one that is "ro" (read only). The code cache graph looks somewhere between the survivor and tenure in shape:


And the permanent areas are close to being flat files (I haven't reproduced them here!)