Java Reference
In-Depth Information
Chapter 11
Garbage Collection
In this chapter, you will learn
•
What garbage collection is
•
How garbage collection is implemented in Java
•
How to pass a hint to the JVM to run the garbage collector
•
How to implement the finalizers
•
Different states of an object based on its reachability and finalization status
•
The difference between strong and weak references
•
How to use weak references to implement memory-sensitive cache
What Is Garbage Collection?
In a programming language, memory management is central to the development of a fast, efficient, and bug-free
application. Memory management involves two activities:
•
Memory allocation
•
Memory reclamation
When a program needs memory, memory is allocated from a memory pool. When the program is finished with
the memory, the memory is returned to the memory pool, so it can be reused by some other part of the program in
the future. The process of returning memory to the pool is known as
memory reclamation
or
memory recycling
. The
memory allocation and reclamation can be accomplished explicitly or implicitly.
In explicit memory allocation, the programmer decides how much memory is needed. The programmer requests
that amount of memory from the program runtime environment known as the
memory allocator
or simply the
allocator
. The allocator allocates the requested memory and marks that memory as in-use, so it will not allocate the
same memory block again. Here, we assumed that our request for new memory block to allocator is always fulfilled.
This can happen only if we have an infinite amount of memory. However, that is not the case with any computer.
Some computers may have megabytes of memory and some may have gigabytes. However, there is always a limit to
the memory available on a computer. If we run a program that always allocates memory blocks from the memory pool
and never returns the memory back to the pool, we will soon run out of memory and the program will stop.
In explicit memory reclamation, the programmer decides when to return the memory to the memory pool.
The allocator is free to allocate the returned memory when it receives a new request for memory allocation. Explicit
memory reclamation often leads to subtle bugs in programs. It also complicates the inter-modules interface design.
Suppose there are two modules, m1 and m2, in an application. Module m1 allocates a block of memory and the
reference to that memory is r1. Module m1 makes a call to module m2, passing the reference r1. Module m2 stores the