Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 13 ■ GARBAGE COLLECTION

Java's garbage collector sweeps the young generation more often than the tenured generations and
uses different collection algorithms for the two generations. Further detail is beyond the scope of this
book. If you're interested in greater detail about Java collection algorithms, you can find a number of
books and web sites devoted to the subject. Efficient garbage collection is one of those problems that
draws the best minds in the field of computer science, because it is both practical (every Java
programmer needs a good one) and highly theoretical.
One of the very difficult issues facing the designers of garbage collection algorithms (including those
used in Java) is how to deal with references that cross the generational boundaries. Before the garbage
collector can remove an object from memory, it has to ensure that no references exist. That means
checking references across the generations, which is a difficult task to do quickly.


Scavenges and Full Collections


The Java garbage collector can do partial garbage collection by collecting just the young generation. This
type of operation is called a “scavenge.” When the garbage collector collects both the young and the
tenured generations, this is called a “full collection,” or (often) just a “collection.” A number of
command-line switches modify the garbage collector's behavior with regard to the young and tenured
generations. We'll encounter these and other switches later in the chapter, in the section entitled
“Understanding Garbage Collection Settings.”


Garbage Collection is Event-Driven xii


Garbage collection doesn't happen every time an object happens to no longer have any references. If it
did, every Java program would spend more time removing unused objects than it would spend doing
anything else, and the performance of all Java programs would be so poor that no one would use Java for
anything.
Instead, the Java garbage collector works on an event-driven model. When certain conditions are
met, the garbage collector runs. These conditions involve the ratio of heap space (the amount of
memory) in use to the amount of free memory and the amount of total memory. In simple terms, when
the JVM determines that it's running out of memory, it runs the garbage collector. So, when the amount
of heap space relative to the amount of total memory gets to a certain percentage, the garbage collector
removes any objects that have no references. Doing so readjusts the percentage of memory in use
downward, so that the program can keep on running.


Understanding Garbage Collection Settings


The Java garbage collector uses another group of switches (similar to the memory switches we saw
earlier) that you set when you start your program. Here's a summary of the most common switches:

Free download pdf