Introduction to Garbage Collection

Last revised On: 07/06/2016 Author Amit Gupta

In this chapter we will understand about Garbage collector in Java and how to request Java for Garbage Collection.

Garbage Collection means that object which are no longer used by program are "garbage" and can be recycled/thrown away. When an object is no longer referenced by the program, the space occupied by the object can be recycled so that it can be used for new objects.

Hence, Java uses Garbage Collector to determine which objects are no longer referenced & runs the finalize() method of the object being freed. In Java, Garbage Collection is done by JVM. Hence you cannot directly free any object rather inform garbage collector to run but it does not guarantee to run. Giving this job to Garbage Collector has several advantages-

  • It can make you more productive where you need not to care about freeing the memory.
  • It helps program integrity in a case where one can incorrectly free memory.

NOTE: Garbage Collector is a daemon thread.

Generally an object becomes eligible for garbage collection when- 

  1.  A reference of any object is set to null.
  2. If an object is created in a block & the control/thread exists that block.

Sample Code to invoke/request Garbage Collection

Invoking the Java garbage collector requires a simple two-step process. First you create a Java Runtime object. If you haven't used them before, Runtime objects let you interface with the environment in which your application is running. Then, after creating the Runtime object, you'll invoke the gc() method ("garbage collector") of the Runtime class.

class DemoColor {
    private String color;

    public DemoColor(String color) {
        this.color = color;
    }

    @Override
    public void finalize() {
        System.out.println("Before Garbage Collection finalize method executed");
    }
}
public class GCDemo {
    public static void main(String[] args) throws InterruptedException {
        DemoColor demo = new DemoColor("Green");
        a = null;
        Runtime.getRuntime().gc();
    }
}

In this chapter we will understand about Garbage collector in Java and how to request Java for Garbage Collection. In our next chapter we will understand finalize() method and its usage in programming.

Author
Author: Amit Gupta
Published On: 21/05/2016
Last revised On: 07/06/2016

Share this chapter
Comments
comments powered by Disqus

Navigation

Social Media