1.

Garbage Collection in Java

Answer»

The Garbage collection in Java DESTROYS all those objects that are not in use any more. So basically, garbage collection helps free the heap memory by removing the unreachable objects i.e. the objects that don’t have any REFERENCE to them.

The different ways that an object is made eligible for garbage collection by the programmer is given as follows:

  1. The reference variable to the object is reassigned.
  2. The reference variable to the object is set is null.
  3. An island of isolation
  4. An object is created inside a method.

After an object is eligible for garbage collection, the garbage COLLECTOR can be run by requesting the Java Virtual Machine. This can be done using the following methods:

  1. The Runtime.getRuntime().gc() method can be called to run the garbage collector by requesting the Java Virtual Machine.
  2. The System.gc() method can be called to run the garbage collector by requesting the Java Virtual Machine.

A PROGRAM that demonstrates running the garbage collector by requesting the Java Virtual Machine is given as follows:

public class Demo {    public static void main(String[] args) throws InterruptedException    {        Demo obj = new Demo();        obj = null;        System.gc();    }    @Override    protected void finalize() throws Throwable    {        System.out.println("The garbage collector is called...");        System.out.println("The object that is garbage collected is: " + this);    } }

The OUTPUT of the above program is as follows:

The garbage collector is called... The object that is garbage collected is: Demo@7978f9b4


Discussion

No Comment Found