Garbage Collection Bootcamp 1.0
Join the DZone community and get the full member experience.Join For Free
table of contents
what is garbage collection
garbage collection in java is the processes of freeing the dynamic memory used by objects that are no longer being used by an application. in languages such as or c or c++, the developer is often responsible for managing dynamic memory (using malloc and free or new and delete ). however, in java, this task is left up to something known as the garbage collector. a garbage collector automatically frees unused memory, freeing the developer from much of this thankless memory juggling.
the most basic garbage collection algorithm works by starting at the root objects (ie objects on the thread stack, static objects, etc) that are live (live meaning currently in use) – and then iterating down over every reachable object. any object that cannot be reached in this manner is garbage and can be collected. the application is paused while this process goes on. this is referred to as mark and sweep – first you mark the objects that are live, then you sweep those that are not. the time needed to do this is obviously proportional to the number of live objects (which can be quite a large number in modern java applications), and so more efficient collection schemes have been devised.
one such scheme comes from the natural fact that you can divide up objects based on how long they live. most applications create a lot of very short lived objects, and fewer objects that are around for a long time (i’ve seen estimates that for the average application, 85-98% of allocated objects are short lived). you can take advantage of this fact when doing collections. in java, objects are allocated from a region of memory known as the heap . the java heap is generally divided up into a few spaces (its usually the same across implementations, but there is the odd exception or two). the major spaces are the young generation, the tenured generation (also called the old generation), and the permanent generation. the young generation is then further sub divided into the eden space and two survivor spaces. the permanent generation is generally for objects that are around for the life of the application (interned strings, class objects, etc) and doesn’t usually play much of a role in garbage collection. the permanent generation size is not part of the heap region defined with -xms and -xmx. though a very unusual need, it is still worth noting that the permanent generation can actually be collected if needed using:
when objects are first created, they are allocated within the eden space. when the eden space becomes full, the still live objects within it are copied into one of the survivor spaces (or if they don’t fit, into the tenured space). one survivor space is always left empty, and on each young generation collection (a minor collection), the live objects from the eden space and the non empty survivor space are copied into the empty survivor space. this leaves a newly emptied survivor space for the next round, as any still live objects in the formerly full survivor space will be copied into the tenured space.
as you can see, rather then running over every object for every collection now, you can collect the young generations more often, and the tenured generation (long lived objects), much less often. you can also optimize your collection for the characteristics of the space – ie usually, almost all of the objects in the young space will be garbage. in general, an object will have to survive a couple minor collections to make it to the tenured space (first making it into a survivor space and then the tenured space). a copying collector identifies garbage by copying live objects from one space to another – anything left over is by definition garbage. the sun jdk uses copying collectors for the young space and mark and sweep type collectors for the tenured space.
tuning for garbage collection means adjusting the sizes of the various spaces mentioned in the previous section, as well as the algorithms used to collect them. you can do this with various jvm command line options.
the amount of ram available for the various spaces is dependent upon the size of the heap that the jvm has allocated. defaults are chosen based on the hardware detected, but you can usually do better by specifying a good xms, xmx yourself. on a server machine, it can be a good idea to pin those two settings together so that the jvm does not waste any time resizing itself. you generally do not want to size the heap much larger than is needed – this can needlessly increase the cost of full garbage collections, and take ram from other important activities, such as file system caching.
|initial heap size|
|maximum heap size|
a note about jvm cmd line options
- boolean options – on : -xx:+<option> off : -xx:-<option>.
- numeric options: -xx:<option>=<number>. numbers can include ‘m’ or ‘m’ for megabytes, ‘k’ or ‘k’ for kilobytes, and ‘g’ or ‘g’ for gigabytes (1m= 1048576). in the case of xms and xmx, only one x is used and no colon.
- string options: -xx:<option>=<string>
you usually want to grant plenty of memory to the young generation – especially when you have multiple processors – as allocation can be parallelized and each thread will get its own private piece of the eden space to work with. you generally want the young generation to have less than half the space of the tenured generation though – especially when using the serialized collector. about 33% is usually a good number to start from. the best size will vary from application to application depending on its distribution of young vs long lived objects. you don’t want the young space to be so small that many short lived objects are getting piled into the tenured space. you also usually don’t want it to be so large that the tenured space doesn’t have enough space available to it and/or young generation collections start taking too long to complete.
other than sizing the total heap, sizing the new generation (another name for the young generation) can be the most important piece to good performance.
|(since 5.0) size of the young generation at jvm startup – this is calculated automatically if you specify newratio|
|(since 1.4) the largest size the young generation can grow to (unlimited if not specified)|
|sets the new generation to a fixed size – this is not usually recommended unless you are fixing the other memory sizes as well.|
|sets the new generation size as a ratio to the tenured generation size.|
|you can also control the sizing of the survivor spaces – in practice this is not usually very helpful though.|
the best sizing is usually chosen by playing with the parameters and then testing the performance of your application. often, the jvm uses good defaults, or depending on the garbage collector in use, resizes the spaces on it’s own based on historical statistics.
there are a few helpful tools that give you insight into the garbage collection process.
you can use the following command line options to generate information about the garbage collection process:
|print info about heap and gc on each collection.|
|(since 1.4) print additional garbage collection info.|
|(since 1.4) add timestamps to the garbage collection logs.|
|specify log file.|
there are various tools to then help you decipher these logs. one is gcviewer – though it only knows how to read gc logs up to java 5.0 (though it can partially read 6.0 files). another nice option from ibm is pmat , and it can read java 6 gc logs.
there is also a very cool tool called visualgc that you can use to visually watch how objects move between spaces in real time as your application is running. this is available as a standalone application, or as a plugin for both netbeans and visualvm .
the garbage collectors
the following applies to the sun java implementation as well as openjdk.
there are three main garbage collection schemes that you should concern yourself with (much of this applies to java 1.4, but in general, i am targeting java 1.5 and up). these schemes are often called collectors themselves, but generally each involves two collectors – one for the old space and one for the new space. these collector schemes are often referred to by their old space collector names: the serialized collector , the throughput collector , and the concurrent low pause collector .
there is also an older incremental collector (unsupported and also called the train collector), and an incremental collection mode for the concurrent low pause collector (that i touch on and is generally used when only one or two cpu’s are available), but i’ll leave those for you to explore on your own if you are interested.
|cmd line arg||
-xx:+useserialgc (since 5.0)
|new space collector||serial – single threaded, stop the world, copying collector|
|old space collector||serial old – single threaded, stop the world, mark-sweep-compact collector|
with the serialized collector, a major collection is done when the tenured space is full. this is known as a “stop the world” collection, because all application threads will be paused while the collection occurs.
this collector is best used with small applications, applications run on a single cpu machine, or applications where pause times don’t matter. this collector is relatively efficient because it does not need to communicate between threads, but you have to be willing to accept its “stop the world” pauses. minor collections will “stop the world” as well, but are generally fairly efficient and fast.
this collector is the only one that i have seen to respect -xx:maxheapfreeratio - though that still only happens if a full collection is triggered. if you where trying to keep your ram usage to a minimum, and always return as much memory as possible to the operating system, using the serialized collector and an aggressive -xx:maxheapfreeratio can be a good strategy. you might want to occasionally force a full collection with system.gc() when your application is idle.
|cmd line arg||
-xx:+useparallelgc (since 1.4.1)
|new space collector||parallel scavenge – multi threaded, stop the world, copying collector|
|old space collector||serial old – single threaded, stop the world, mark-sweep-compact collector|
the throughput collector uses a parallel version of the young generation collector, while the tenured generation will still use the serial collector. so while a single thread will still perform collections on the tenured space, multiple threads will work together collecting the young space.
a feature called parallel compaction was added in java 1.5 update 6 – this feature allows the throughput collector to also perform major collections in parallel. you can enable this with -xx:+useparalleloldgc . using this should help a lot with scalability, as you sidestep the single collection thread bottleneck on very large heaps (multi gigabyte). i’ve read this can actually lower performance on smaller heaps due to lock contention.
the throughput collector should be the default collector chosen on server class machines (in java 1.5 and up), but there are exceptions – for example, my macbookpro defaults to the cms collector. you can always override these defaults.
throughput is usually most useful when your application has a large number of threads creating new objects, and you have more than one processor available (though more than two is best). typically, when you have multiple threads allocating objects, you also want to increase the size of the young generation. the number of garbage collector threads will generally be equal to the number of processors you have, but you can control that number with -xx:parallelgcthreads =n. sometimes you will want to lower the number of threads because each will reserve a part of the tenured generation for promotions – this can cause a fragmentation effect and effectively lower the size of the tenured generation (this is generally only an issue if your application has access to many processors or cores).
the throughput collector also supports something called ergonomics. as part of this support, you can specify various desired behaviors for your application, and the jvm will attempt to tune various settings to meet your goals.
-xx:maxgcpausemillis =n hint to the throughput collector that a max pause time of n milliseconds is desired. by default there is no hint. the collector will adjust the heap size and other collection parameters in an attempt to meet the hint – keep in mind that throughput may be sacrificed in the attempt to meet this goal. there is also no guarantee that the goal will be met.
you can also specify a target goal for how much time is spent in garbage collection in comparison to running your application using -xx:gctimeratio . by default this is set to 1% (keep in mind that these defaults tend to change from release to release).
with the serialzed garbage collector a generation is collected when it is full (i.e., when no further allocations can be done from that generation). this is also true of the throughput collector.
|cmd line arg||
-xx:+useconcmarksweepgc (since 1.4.1)
|new space collector||par new – multi threaded, stop the world, copying collector that works with cms|
|old space collector||usually cms , the mostly concurrent low pause collector – unless there is a concurrent mode failure, in which case, serial old - single threaded, stop the world, mark-sweep-compact collector|
use the concurrent low pause collector when you can afford to share the processor resources with the garbage collector while the application is running. this is usually good for an application with a lot of long lived data – meaning you need a large tenured generation space. obviously, having multiple processors is also helpful. this collector still pauses the application threads twice in a collection – once briefly at the start (when it marks objects directly accessible from root objects), and a slightly longer pause towards the middle (when it sweeps to find what it missed due to parallel marking) – the rest of the collection is done concurrently using one of the available processors (or one thread). if this collector cannot complete collecting the tenured space before it is full, all threads will be paused and a full collection performed – this is known as a concurrent mode failure and likely means you need to adjust the concurrent collection parameters.
this collector is used for the tenured generation, and does the collection concurrently with the execution of the application. this collector can also be paired with a parallel version of the young generation collector ( -xx:+useparnewgc ).
note that - xx:+useparallelgc (the throughput collector) should not be used with -xx:+useconcmarksweepgc , and the jvm will fail on startup if you try this with most modern jvms. same with -xx:+useparalleloldgc .
the concurrent low pause collector will keep statistics so that it can best guess when to start collecting (so that it finishes before the tenured space is full) – also though, it will start collecting when the tenured space hits a percentage of what’s available – you can manually set this with -xx:cmsinitiatingoccupancyfraction =n. the default for this setting varies across jvms. i’ve read that the default for 1.5 was 68%, while the default for 1.6 is 92%. you can lower this if needed to ensure that the collection is kicked off sooner, and then you will be more likely to finish the collection before the tenured space is full.
the concurrent low pause collector can also be used in an incremental mode that i will not go into here. this mode causes the low pause collector to occasional yield the processor used for parallel collection back to the application, and thereby lessen its impact on application performance.
the parallel young generation collector
this collector is much like the throughput collector in that it collects the young generation in parallel. most of what applies to the throughput collector also applies to this collector, however a different implementation is used that allows this collector to work in conjunction with the concurrent low pause collector, unlike the throughput collector. despite some sun/oracle literature indicating this is off by default, it does seem to be on by default when using cms in at least java 6. you can disable it with:
the flip side of that coin is that while the throughput garbage collector ( -xx:+useparallelgc ) can be used with adaptive sizing ( -xx:+useadaptivesizepolicy ), the parallel young generation collector ( -xx:+useparnewgc ) cannot.
-xx:+useadaptivesizepolicy records statistics about gc times, allocation rates, and free space, and then sizes the young and tenured generations to best fit those statistics. this is for use with the throughput collector and is on by default.
note: this article is biased towards server applications and the -server hotspot vm.
usually you just want to start with the parallel (throughput) collector. it’s the one that has ergonomics, and it will automatically adjust key settings so that most server apps will do just fine. this is the default collector on most server class systems. in general, you do not need to change any garbage collection settings until you have determined you have a garbage collection issue to solve.
when you have to confront very large heaps, the parallel collector can start to break down – it collects the tenured space using a stop the world collection, meaning your app is frozen while the collections happens. so when you find that the parallel collector is just not cutting it, even when using useparalleloldgc , you might try the mostly concurrent low-pause collector. it will collect as your application is running using a thread on the side, with two much shorter stop-the-world pauses. overall, the cms collector is slower in terms of throughput – but your application will likely be frozen less often.
ergonomics do not apply here, so you are on your own for coming up with good settings if the defaults don’t turn out to be a good fit – but you can often remove long “the world is stopped” pauses with this collector.
the hope is that it is just going to make sense to always use the g1 collector in the future – it attempts to offer the best of both worlds of the throughput and mostly concurrent low pause collectors.
the garbage first (g1) collector
the garbage first collector is a new garbage collector that intends to rule them all. it is available in sun java 6 update 14 as well as recent versions of openjdk6 and early versions of openjdk 7. eventually i plan to write more about his collector. briefly: the g1 collector should combine the best of both the throughput and mostly concurrent low pause collectors. it uses new strategies to minimize stop the world pauses and maintain high throughput on multiprocessor systems with very large heaps.
try this collector with:
Published at DZone with permission of Mark Miller. See the original article here.
Opinions expressed by DZone contributors are their own.