C++, it was up to the programmer to explicitly free up such memory. Java is the first widely
keeps track of when an object will no longer be used and automatically frees up the memory
space taken up by those objects.
You would think that cleaning up objects (and therefore freeing up memory) when a program
is finished with the object would be a straightforward thing to do, and so automating that pro-
cess shouldn't be that big a deal. If we were writing simple programs in which the lifetime of
an object was easy to track, this might be the case. After all, this seems not that different from
picking your socks up off the floor and putting them in the hamper, or recycling the soda cans
that accumulate in your office (although programmers have the reputation for not being very
good at either of these tasks).
The fact is that it is difficult to keep track of when and how to clean up the memory used by
objects. There are the easy cases where an object is created at the beginning of a method, gets
used inside of that method, and then is never used again when that method is finished. But
most of the time when an object is created, it is handed to some other part of the program.
That part of the program may store a reference to the object in some other object, which then
gets handed to some other part of the program. Worse yet, a reference to the object might be
stored in multiple objects, in which case it is up to the programmer working in a language that
does not have garbage collection to keep track of when the last reference is gone so that the
object can be cleaned up. Programmers have to make it clear in routines that create objects
which one is responsible for deleting those objects and under what circumstances. Get rid of
an object too soon, and those who think they have a reference to a still-existing object will (if
they are lucky) have a reference to nothing, or (if they are unlucky) have a reference to a new
object, which may have nothing in common with the old object.
Studies done around the time of the introduction of the Java language claimed that over half
Not only are such bugs common, but they also are notoriously difficult to track down. An ef-
fect of a memory leak or the use of memory that has already been freed often cannot be seen
until well after the code that caused the problem was run, and would often go away when the
problematic program was run in the debugger (because the debugger would move the program
to a different location in memory). Tools have been invented that track the use of memory,
and will tell a programmer when some piece of memory is reused too early or not freed at
all. While these tools identify the problems, they don't help a programmer solve the problem.
Knowing that you aren't freeing up some memory is a first step in finding the problem, but
the real problem is determining where and when you can discard the memory used. Garbage