Java Reference
In-Depth Information
Chapter 5. Garbage Collection
So far, we have identified a number of good parts of the Java language and environment that
allow us to write modular, maintainable code, often with the help (or at least the participa-
tion) of lots of other people. All of these good things allow us to do something—define a type,
either as a class or an interface; define and handle an exception (and tell others when to expect
such an exception); or create a package that both defines a separate namespace and interacts
with the protection mechanisms to give you a layer of abstraction.
Now we are going to turn to a good part of Java that lets us not do something. In the early days
of Java, I used to ask people if they would be willing to try a programming tool that would fix
over half of the bugs in their code. They were always eager to get such a tool; when I pointed
out that it was Java, they were confused. The part of Java that allowed this claim (and still
allows it) is garbage collection. Because of this feature, you don't have to do explicit memory
management within your program, and flaws in such memory management have been shown
to be a large fraction of the bugs in programs written in languages that don't have garbage
Even though garbage collection is a feature that allows you to not do things, there are still
some things that you have to understand to use the feature correctly. There are still ways to
defeat the garbage collector and produce a memory leak. And habits from other languages,
which conflate memory management with other forms of resource management and reclam-
ation, don't translate well to Java. So we will talk about a feature that, at its best, should be
The Basics
The basics of garbage collection, at least from the programmer's view, are pretty simple. [ 14 ]
Objects take up space in the memory of a computer. When we first create those objects, that
memory is allocated. But memory is a finite resource. While memory is not nearly so finite
these days as it used to be, we programmers have been very clever at using it up faster than the
computer manufacturers can add it to systems. So when we are done with an object, we would
like that memory to be reclaimed so it can be used for something else. In languages like C and
Search WWH ::

Custom Search