Invoking GC
Invoking GC
Note: This article is very old, like 1990s-old. In the 90s we did things like this, but manually
manipulating theJava garbage collector in the 201x years is not a best-practice. That being said, I'm
leaving this article here for historical reasons.
Summary: This article demonstrates how to use the Java Runtime class to invoke the Java garbage
collector, and shows the results of running the Java Runtime freeMemory method in an example
class.
Introduction
As you know, the Java Virtual Machine (JVM) takes care of memory management for you. That's one
of the beauties of Java - life as a Java developer is easier than C/C++ because you don't have to
worry (as much) about memory management, and making all of the mistakes associated with
memory management, such as forgetting to free dynamically allocated memory.
Generally speaking (and ignoring the differences between implementations and versions) the JVM
works by performing garbage collection when it needs more memory to continue execution. Though
your program may lose a reference to an object - thereby making it a candidate to be reclaimed -
there's no guarantee the JVM will reclaim that memory.
Although you can't tell Java to explicitly reclaim the memory of a specific de-referenced object, there
is a way to tell the JVM to perform garbage collection, which may result in the desired memory being
reclaimed. It's a very simple technique, and I was inspired to use it when I was developing a Java-
based editor on a computer with limited memory itself.
Invoking the Java garbage collector requires a simple two-step process. First you create a
Java Runtime object. If you haven't used them before, Runtime objects let you interface with the
environment in which your application is running. Then, after creating the Runtime object, you'll
invoke the gc() method ("garbage collector") of the Runtime class.
Listing 1 shows a simple program that tests this technique. Although it may look
a little complicated, all we do is grab a bunch of memory and then release it. At
various stages in the program, we use the freeMemory() method of the Runtime
class to determine the amount of free memory in the system.
public class GCTest {
void eatMemory() {
L isting 1 (above): The GCTest program (GCTest.java) demonstrates how you can manually invoke
the garbage collector of the JVM.
To compile this program at the command line, just enter this command:
javac GCTest.java
Then, when you're ready to run the program, use this command to invoke the Java interpreter (the
JVM):
java GCTest