Free Data Structures and Algorithms Course

Subscribe below and get all best seller courses for free !!!


Subscribe to all free courses

How Garbage Collection works in Java ?

Introduction :- 
Garbage Collection is an important concept in Java programming language which deals with the removal of unwanted objects from the heap memory. This concept is applied by Java Virtual Machine which automatically cleans object from the heap memory when they are unused. If we talk about heap memory, it is an special and large pool area of memory. It has unused memory and usually store Java objects used in Java applications. The size of heap memory depends on the environment. The heap memory can store large chunks of objects, but if it keeps on storing more and more objects finally it can run out of memory.
Usually JVM performs automatic garbage collection of objects which are unreachable in our application. Garbage Collection is performed by Garbage Collector present in JVM. There is no specific algorithm followed by Garbage Collector to free memory by removing unwanted objects stored on heap. JVM implements different algorithm to determine the time and efficiency of performing Garbage Collection. The main thing we should keep focus on is the point when object becomes free, unreachable and unused for garbage collection.

Generally, new keyword is used to create a new object on heap dynamically. It also returns a reference value of an object in memory. We save this value in a variable which we can use to refer to that object later. Garbage Collector performs many tasks such as :
  1. It has a track of object references. 
  2. It frees memory when an object is unreachable from its reference. 
  3. It uses free memory to allocate new objects.
  4. It finally invokes finalize method. 
Garbage Collector can/ may be invoked by two ways :
  1. Using Runtime class instance and invoking gc method through it. 
  2. Using the System class gc method to invoke it. 
Program to demonstrate the use of garbage collector : 

package com.hubberspot.garbagecollection.example;

 * @author jontymagicman

public class GarbageCollector {
  public static void main( String[] args){
    Runtime rt = Runtime.getRuntime();
    System.out.println("Total JVM memory "
            + "available = "+ rt.totalMemory());
    System.out.println("Free memory before "
            + "Garbage Collection = " + rt.freeMemory());
    System.out.println("Free memory after "
            + "Garbage Collection = " + rt.freeMemory());
Output of the program : 

© 2021 Learn Java by Examples Template by Hubberspot