Java Reference
In-Depth Information
Chapter 5. An Introduction to Garbage
Collection
This chapter covers the basics of garbage collection within the JVM. Short of rewriting code,
tuning the garbage collector is the most important thing that can be done to improve the per-
formance of a Java application.
There are four main garbage collectors available in current JVMs: the serial collector (used
for single-CPU machines), the throughput (parallel) collector, the concurrent (CMS) collect-
or, and the G1 collector. Their performance characteristics are quite different, so each will be
covered in depth in the next chapter. However, they share basic concepts, so this chapter
provides a basic overview of how the collectors operate.
Garbage Collection Overview
One of the most attractive features of Java is that developers needn't explicitly manage the li-
fecycle of objects: objects are created when needed, and when the object is no longer in use,
the JVM automatically frees the object. If, like me, you spend a large amount of time optim-
izing the memory use of Java programs, this whole scheme might seem like a weakness in-
stead of a feature (and the amount of time I'll spend covering GC might seem to lend cre-
dence to that position). Certainly it can be considered a mixed blessing, though I'd say I've
personally spent less time dealing with Java memory issues in the past 15 years than I spent
during 10 years of finding and fixing bugs caused by dangling and null pointers in other lan-
guages.
At a basic level, GC consists of finding objects that are no longer in use, and freeing the
memory associated with those objects. The JVM starts by finding objects that are no longer
in use (garbage objects). This is sometimes described as finding objects that no longer have
any references to them (implying that references are tracked via a count). That sort of refer-
ence counting is insufficient, though: given a linked list of objects, each object in the list (ex-
cept the head) will be pointed to by another object in the list—but if nothing refers to the
head of the list, the entire list is not in use and can be freed. And if the list is circular (i.e., the
Search WWH ::




Custom Search