Java 7 for Absolute Beginners

(nextflipdebug5) #1

C H A P T E R 1 3


249

Garbage Collection


Java relies on garbage collection. A garbage collector removes unused objects from memory and lets
your programs re-use memory rather than constantly grow. For very small programs, this constant
growth doesn't matter much. However, even a program of fairly low complexity and scale can quickly
chew through a lot of memory. Therefore, most programs really need some kind of garbage collection
mechanism.
When they use many other languages, including C++, programmers have to manage memory
themselves, writing code to remove objects from memory at the right time. Java frees developers from
this problem. That's not to say that Java is better than C++. Both languages have their strengths and
weaknesses. Many developers who prefer Java would tell you that having to manage memory yourself is
a weakness in C++ and that garbage collection is a strength of Java. Conversely, many C++ developers
would tell you the opposite. Both are true: Garbage collection can be a problem in Java, yet is also an
inherent feature and very powerful if managed correctly.
So how do we turn garbage collection into an advantage rather than a burden?


Understanding Memory Allocation


Before we can really talk about garbage collection, we need a basic understanding of how the Java Virtual
Machine (JVM) allocates memory in the first place. Every time you create a new object or primitive, the
heap grows by the size of that object or primitive. In addition, if you create a complex object (an object
that itself contains other objects, as many objects do), the heap grows by the size of all those objects as
well. For example, consider a class we've seen before (in the previous chapter), the TargetClickPanel
class:


Listing 13-1. Memory Allocation in the TargetClickPanel Class


package com.bryantcs.examples.videogames;


import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;


import javax.swing.JPanel;


Java 7 for Absolute Beginners
© Jay Bryant 2012

J. Bryant,
Free download pdf