Garbage Collection

From Wiki
Jump to navigationJump to search


  • 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.

Strings GC

  • String literals - those Strings that are in the pool are not eligible for GC. (A reference from the pool will always be there to the object). How the pool memory is managed is a different question, I suppose.
  • Strings from the heap, like any other object will be eligible for GC.

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 when it ran finalize() and will not run it again. (However, finalize() can be called manually many times!)
  • Enum classes cannot have finalize() methods.
  • Finalizers are not chained explicitly like constructors are. So a subclass finalizer needs to invoke super.finalize() explicitly.
  • Runtime.getRuntime().runFinalization() / System.runFinalization() can request for any pending finalizers be run for objects eligible for GC.
  • This is the idiom to call finalize. Note when calling super.finalize there is a Throwable that must be dealt with.
public void finalize() throws Throwable {
		System.out.println("Finalizing... " + this);
		try {
		} finally {


  • The JVM uses a JIT compiler. The code is compiled as it is executed.
  • JIT compilers create profiling data and make compiler decisions on the fly.
  • Allocation leads to Garbage Collection. Is done on a per-thread basis on the heap.
  • To avoid same address space being allocated to multiple threads, heap lock is required, but is expensive.
  • In multicore systems, not feasible. So partition the heap into Thread Local Areas within which a Thread can allocate freely.
  • Once the heap is full though, GC kicks in.