Thursday, May 18, 2017

Garbage Collection in Java

All about Garbage Collection in Java/Android.


In other programming language, it is programmer’s responsibility to delete a dynamically allocated object if it is no longer in use.

In Java, the programmer need not to care for all those objects which are no longer in use. Garbage collector destroys these objects, but the garbage collector is not guaranteed to run at any specific time, it can be at any time once an object is eligible for garbage collection.


Following are some important points related to garbage collection:

The finalize () method:

Called by the garbage collector on an object when garbage collector determines that there are no more references to the object.

The finalize method is never invoked more than once by a Java virtual machine for any given object.
Our program must not rely on the finalize method because we never know if finalize will be executed or not.

Ways to make an object eligible for garbage collection:

Once the object is no longer used by the program, we can change the reference variable to a null, thus making the object which was referred by this variable eligible for garbage collection.
Please note that the object can not become a candidate for garbage collection until all references to it are discarded.

class Test
{
    public static void main(String[] args)
    {
        Test obj = new Test();

        /* obj being used for some purpose in program */

        /* When there is no more use of o1, make the object
           referred by o1 eligible for garbage collection */      
        obj = null;

        /* Rest of the program */
     }
}


gc() – request to JVM:

We can request to run the garbage collector using java.lang.System.gc() but it does not force garbage collection, the JVM will run garbage collection only when it wants to run it.

We may use system.gc() or runtime.gc()

import java.lang.*;
public class Test
{
    public static void main(String[] args)
    {
        int g1[] = { 0, 1, 2, 3, 4, 5 };
        System.out.println(g1[1] + " ");

        // Requesting Garbage Collector
        System.gc();
        System.out.println("Hey I just requested "+
                          "for Garbage Collection");
    }
}


I have a question?

What happens when group of object only refer to each other?

Ans: It is possible that a set of unused objects only refer to each other.For example, object o1 refers to object o2. Object o2 refers to o1. None of them is referenced by any other object. In this case both the objects o1 and o2 are eligible for garbage collection.All this process is called Island of Isolation.

eg: public class Test
{
    Test geek;
    public static void main(String [] args)
    {
        Test o1 = new Test();
        Test o2 = new Test();
        o1.geek = o2;
        o2.geek = o1;

        o1 = null;
        o2 = null;
       // both become eligible for garbage collection
    }
}

No comments: