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 participation) 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 collection.

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, ...

Get Java: The Good Parts now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.