Garbage Collection

  • In java, garbage means unreferenced objects.
  • Garbage Collection is process of reclaiming the runtime unused memory automatically.

Advantage of Garbage Collection:

  • It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  • It is automatically done by the garbage collector so we don’t need to make extra efforts.

How can an object be unreferenced?

There are many ways:
  • By nulling the reference
  • By assigning a reference to another
  • By annonymous object etc.

1) By nulling a reference:

2) By assigning a reference to another:

3) By annonymous object:

finalize() method:

The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in System class as:

Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

gc() method:

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection:

Note: Neither finalization nor garbage collection is guaranteed.