Garbage Collection

From Suhrid.net Wiki
Jump to navigationJump to search

Introduction

  • All GC involves in making sure the heap doesnt run out of space.
  • Purpose of the GC is to find and delete objects that cannot be reached.
  • An object is eligible to be garbage collected when no live thread can access it.

Ways in which Objects can be GC'ed

  • Nulling a reference - Explicitly assigning a reference to null will make it eligible for GC.
  • Reassigning a reference - Reassigning the reference to another object will cause older object to be eligible for GC.
    • Local variables in a method will be eligible for GC when the method returns.
  • Isolating a reference - Even if objects have valid references, but still there is no way to reach them, they will be GC'ed.

Invoking GC

  • Just a request, no guarantee that GC will happen.
  • Runtime.getRuntime().gc() or System.gc() as a convenience method.

Finalize Method

  • Any code that needs to be run before the object is GC'ed can be included in the finalize() method.
  • The finalize() method is defined in Object. (protected void finalize() throws Throwable)
  • For any object, finalize() will called ONLY ONCE by the GC. (An object can be gc'ed only once!)
  • Sometimes calling finalize() can cause the object not to be GC'ed if a reference to the current object is assigned somewhere else.
  • Any exception thrown but not caught by a finalizer that is called by the GC will be ignored.
  • The JVM remembers that finalize() already ran and will not run it again.
  • Enum clases cannot have finalize() methods.
  • Finalizers are not chained explicitly like constructors are. So a subclass finalizer needs to invoke super.finalize() explicitly.