AppDividend
Latest Code Tutorials

Garbage Collection in Java Example | Java Garbage Collection

0

Garbage Collection in Java Example | Java Garbage Collection is today’s topic. The concept of Garbage Collection in Java was implemented to automate the heap memory management during the execution of any Program. Due to this feature of Java, unlike C or C++, we need not worry about de-allocating the memory manually. This makes Java a memory efficient programming language.

Garbage Collection in Java

Garbage collection in Java is one of the advanced topics. Java GC knowledge helps us in the tuning our app runtime performance. In Java, the programmers don’t need to destroy the objects that have no use. The Garbage Collector takes care of it. The Garbage Collector is the Daemon thread that keeps running in the background. It frees up a heap memory by destroying the unreachable objects.

#Working of Garbage collection

Now, let us understand the entire working behind the Java Garbage collection concept. Whenever you create an object reference, no memory is provided to it in the heap memory until you specify it using the new keyword. 

For example, in the following statement, suppose Student is a class, and we want to create an object of this class.

Student obj;

Here, the object obj is only a reference to the object, and it occupies no space inside the heap memory. So, to allocate memory to it, you have to manually instruct the compiler to do so, as in the following statement.

Student obj= new Student();

Now what happens here is that an object variable is created in the stack memory which stores some hash value. This hash value is the location of this object inside the heap memory.

Now, this object remains inside the heap memory until its reference variable exists in the stack memory. As soon as the reference variable is nullified or its hash value is replaced by some other hash value (which happens in the case when we provide some new value for the same reference variable), then in those cases, that object is available for garbage collection. What this means that, now this heap memory can be reallocated to other variables and objects.

#How Automatic Garbage Collection works

Automatic Garbage collection is the process of looking at a Heap memory, identifying the unreachable objects, and destroying them with the compaction. The issue with this tackling method is that, as a number of objects increases, the Garbage Collection time keeps on increasing as well and as it needs to go through an entire list of the objects, looking for an unreachable object.

However, an empirical analysis of applications shows that most of the objects are very short-lived. This behavior was used to improve a performance of Java Virtual Machine, and the adopted methodology is commonly called as the Generational Garbage Collection. In this method, the Heap space is divided into the generations like a Young Generation, Old or Tenured Generation, and Permanent Generation.

The Young generation heap space is new where all the new Objects are created. Once it gets filled up, the minor garbage collection (also known as, Minor GC) takes place. Which means that, all the dead objects from this generation are destroyed. This process is very quick because as we can see from the graph, most of them would be dead already. 

The Old Generation is used to save the long surviving objects. Typically, the threshold is set for the young generation object, and when that age is met, the object gets moved to an old generation. Eventually, an old generation needs to be collected. This event is called the Major GC (major garbage collection). It is much slower because it involves all the live objects.

#Example and applicable area

Following are some examples where the non-reference variables exist, and the concept of garbage collection is applied:

#Whenever a variable goes out of scope

See the following example.

public class Gc1 {
    public static void main(String args[])
    {
        int a=0;
        for(int i=1;i<=5;i++)
        {
            a=a+i;
            int b=i;
            System.out.println("\n"+a+" "+b);
        }
    }
}

See the following output.

 

Garbage Collection in Java

Here, the scope of variable b remains only within the body of for loop, and as soon as the for loop gets completed, the variable b is available for garbage collection, as it is now out of scope.

#Whenever an object goes out of scope

See the following code.

class Stu {
    Stu() {
        System.out.println("\nHello Student");
    }
}

public class Gc2 {
    public static void Greet() {
        Stu obj = new Stu();
    }

    public static void main(String[] args) {
        int no_of_students = 5;
        for (int i = 0; i < no_of_students; i++) {
            Greet();
        }
    }
}

See the following output.

 

Whenever an object goes out of scope

Here, the scope of the obj variable is only within the body of the ‘Greet’ method, and as soon as the execution of method Greet is completed, the object obj is available for garbage collection. It should be noted that whenever this method ‘Greet’ is called, it creates a new object again and again, which does not denote the previously created object, although the name of the created is the same every time.

#Whenever the value of the variable is overwritten

See the following code.

public class Gc3 {
    public static void main(String[] args) {
        int a=5;
        System.out.println("\n"+a);
        a=10;
    }
}

See the output.

 

Whenever the value of the variable is overwritten

In this case, the value of a, which was initially 5, is being overwritten by the value 10. So, the previous value which is present inside the heap memory has no reference, and so it is available for garbage collection.

#Whenever a new memory is allocated to the reference object

See the following code example.

class Student {
    Student() {
        System.out.println("\nHello Student");
    }
}

public class Gc4 {
    public static void main(String[] args) {
        int no_of_students = 5;
        Student obj;
        for (int i = 0; i < no_of_students; i++) {
            obj = new Student();
        }
    }
}

See the following output.

 

Whenever a new memory is allocated to the reference object

Here, every time the for loop executes, new memory is being allocated to the object reference obj, and the previous object becomes non-referenced simultaneously and is thus available for garbage collection. 

#Requesting to run Garbage Collector

Whenever the garbage collector is invoked for destroying any object, the finalize method is called. This finalize method is present inside the Object class.

It has the following syntax.

protected void finalize() throws Throwable

The garbage collector can also be called manually using the System.gc() or Runtime.getRuntime.gc() method. The following code shows the working of both the gc() method and the finalize() method.

See the following program.

public class Gc5 {
    int a = 10;

    public static void main(String[] args) {
        Gc5 obj = new Gc5();
        System.out.println(obj.a);
        obj = null;
        // System.out.println(obj.a);
        // Note: Here, no value for a is printed and it will throw exception, as the
        // object obj contains a null value now
        System.gc();
        // calling the garbage collector on demand;
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("Garbage Collector Working");
    }
}

See the following output.

 

Requesting to run Garbage Collector

#Final Program of Garbage Collector

public class GC {
  public static void main(String[] args) throws InterruptedException {
    GC g = new GC();
    GC gl = new GC();

    // Nullifying the reference variable
    g = null;

    // requesting JVM for running Garbage Collector
    System.gc();

    // Nullifying the reference variable
    gl = null;

    // requesting JVM for running Garbage Collector
    Runtime.getRuntime().gc();
  }

  @Override
  // finalize method is called on object once
  // before garbage collecting it
  protected void finalize() throws Throwable {
    System.out.println("Garbage collector called");
    System.out.println("Object garbage collected : " + this);
  }
}

See the following output.

 

Garbage Collection in Java Example | Java Garbage Collection

Finally, the Garbage Collection in Java Example | Java Garbage Collection is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.