Java Reference
In-Depth Information
many references there are to an object and then frees the object
when the reference count is zero. However, it is easy to come up
with a situation in which two objects need to be garbage collected,
but each object has a reference to the other. If reference counting
was being used, these two objects would never be freed.
Q: Then how do you make an object unreachable?
A: You need to make sure that the references that are still within the
scope of your Java application are no longer referring to the object
you want to be garbage collected. You can assign these references
to null, assign them to point to some other object, or make the ref-
erences go out of scope.
Q: Suppose that I have a very large object that I have just made
unreachable and I want it to be garbage collected right now. Can I
force the garbage collector to free the memory instantly?
A: Unfortunately, no. In Java, you cannot explicitly free memory.
However, there is method you can invoke, System.gc(), which
causes the garbage collector to “expend effort towards recycling
unused objects,” as quoted from the method's documentation.
The gc() method is very much JMV dependent, so its behavior is
hard to predict. However, it is your only mechanism for communi-
cating with the garbage collector.
The following GCDemo program instantiates three Employee objects. Study
the program carefully and try to determine at which point in the program that
each Employee will be eligible for garbage collection.
public class GCDemo
{
public static void main(String [] args)
{
Employee e1, e2, e3;
e1 = new Employee(); //Employee #1
e2 = new Employee(); //Employee #2
e3 = new Employee(); //Employee #3
e2 = e1;
e3 = null;
e1 = null;
}
}
Search WWH ::




Custom Search