Java Reference
In-Depth Information
specifi cation does not defi ne how a garbage collector accomplishes the task of freeing
memory. The specifi cation only states that when an object is eligible for garbage collection,
the garbage collector must eventually free the memory.
As a Java coder, you cannot specifi cally free memory on the heap. You can only ensure
that your objects that you no longer want in memory are no longer reachable. In other
words, make sure you don't have any references to the object that are still in scope.
The following section discusses the System.gc method, which provides a small amount
of control over freeing memory on the heap.
The System.gc Method
The java.lang.System class has a static method called gc that attempts to run the garbage
collector. System.gc is the only method in the Java API that communicates with the
garbage collector. Here is what the Java SE API documentation says about the System.gc
method:
Calling the gc method suggests that the Java Virtual Machine expend
effort toward recycling unused objects in order to make the memory they
currently occupy available for quick reuse. When control returns from the
method call, the Java Virtual Machine has made a best effort to reclaim
space from all discarded objects.
In other words, the gc method does not guarantee anything! The method might be
useful if you are familiar with the intricate details of your JVM and how it implements
this method. But the end result is that as a Java programmer you cannot free memory
specifi cally in your code. You can only ensure that your objects are eligible for garbage
collection, and then assume the garbage collector will do its job!
Let's look at another example typical of a question found on the exam. Examine
the following code and determine when the String objects become eligible for garbage
collection and when they actually get garbage collected:
1. public class GCDemo2 {
2. public static void main(String [] args) {
3. String one = “Hello”;
4. String two = one;
5. String three = “Goodbye”;
6.
7. three = null;
8. System.gc();
9. one = null;
10. System.gc();
11. two = null;
12. }
13. }
Search WWH ::




Custom Search