Image

Java - Core Java - Garbage Collection

Garbage Collection

The process of destroying unreferenced objects is called garbage collection. After object is unreferenced it is considered as unused object so that JVM automatically destroys that unused object. In Java, developer’s responsibility is only creating object and unreferencing those objects their usage. So that JVM takes care of destroying those unreferenced objects.

Java.lang.OutOfMemoryError

If we want to create objects and there is no space in heap area then JVM terminates program execution and throw the exception “java.lang.OutOfMemoryException”. To utilize memory effectively developer must unreferenced objects after their usage.

How can JVM destroy unreferenced object?

Internally JVM uses a daemon thread called “garbage collector” and it destroy all unreferenced objects. A daemon thread is a background service thread. Garbage collector is called daemon thread because it provides services JVM to destroy unreferenced objects in background.

This thread has a low priority that is we cannot guarantee this thread execution.

No, we cannot guarantee objects destruction even though it is unreferenced, because we cannot guarantee garbage collector execution. We can only confirm that whether object is eligible for garbage collection or not. We cannot force Garbage collector to destroy objects, but we can request it.

How can we request JVM to start garbage collection process in java?

In java we have a gc() method of System class and declared static

Calling gc():
System.gc()
Runtime.getRuntime().gc()
 
For Example
class GarbageCollection
{
    public static void main(String[] arg) throws InterruptedException
    {
        GarbageCollection t1 = new GarbageCollection();
        GarbageCollection t2 = new GarbageCollection();
         
        // Nullifying the reference variable
        t1 = null;
         
        // requesting JVM for running Garbage Collector
        System.gc();
         
        // Nullifying the reference variable
        t2 = null;
         
        // requesting JVM for running Garbage Collector
        Runtime.getRuntime().gc();
    
    }
     
    // finalize method is called on object once 
    // before garbage collecting it
    protected void finalize() throws Throwable
    {
        System.out.println("Garbage collector is called");
        System.out.println("Object garbage is collected : " + this);
    }
}