12/19/2008

Garbage collection

Java garbage collection destroys objects as follows:

  • Objects that nothing refers to
  • Objects that nothing can refer to.


Set an object to ‘null’
If you set a variable to null, then it refers to nothing and the garbage collection destroys this object.

Set an object to another value
If you set a variable to another value, the object previously referred to becomes a target of the garbage collection.

Integer a = new Integer(1);
Integer b = new Integer(2);
a = b;

At this time, nothing refers to the instance ‘new Integer(1)’ and thus it becomes a target of the garbage collection.

Isolate references

= null
= null

The garbage collection targets them.

Can we execute a garbage collection immediately?
No.
You can only request a garbage collection.
When to execute it depends on JVM.
 
Request a garbage collection
・ System.gc();
・ Runtime.getRuntime().gc();

finalize method
 A finalize method is invoked just before the garbage collection destroys an object.
A finalize method is invoked once for each object.
It is not recommended to write important procedure in a finalize method.