< Java Tutorial

Java garbage collection

← Previous Next →

In Java destruction of object from memory is done automatically by the JVM.
When there is no reference to an object, then that object is assumed to be no longer needed and the memory occupied by the object are released.
This technique is called Garbage Collection. This is accomplished by the JVM.

Unlike C++ there is no explicit need to destroy object. 

Advantages of Garbage Collection

  • Programmer doesn't need to worry about dereferencing an object.
  • It is done automatically by JVM.
  • Increases memory efficiency and decreases the chances for memory leak.

finalize() method

Sometime an object will need to perform some specific task before it is destroyed such as closing an open connection or releasing any resources held.
To handle such situation finalize() method is used.  finalize()  method is called by garbage collection thread before collecting object. Its the last chance for any object to perform cleanup utility.

Syntax of finalize() method

protected void finalize()

Some Important Points to Remember

  • finalize() method is defined in java.lang.Object class, therefore it is available to all the classes.
  • finalize() method is declare as proctected inside Object class.
  • finalize() method gets called only once by GC threads.

gc() Method

gc() method is used to call garbage collector explicitly. However gc() method does not guarantee that JVM will perform the garbage collection. It only request the JVM for garbage collection. This method is present in System and Runtime class.

Example for gc() and finalize() method

public class Test
    public static void main(String[] args)
        Test t = new Test();
        System.gc(); // force call of garbage collector

    public void finalize()
        System.out.println("Garbage Collected");

Garbage Collected

← Previous Next →