How Garbage Collection Works In Java ?

Introduction :-

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 :

It has a track of object references.
It frees memory when an object is unreachable from its reference.
It uses free memory to allocate new objects.
It finally invokes finalize method.
Garbage Collector can/ may be invoked by two ways :

Using Runtime class instance and invoking gc method through it.
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());


For more of such hot topics read my other posts here :

Visit my new website

Article Written By jontymagicman

I am DInesh Varyani.

Last updated on 26-07-2016 106 0

Please login to comment on this post.
There are no comments yet.
Program To Demonstrate How To Swap Two Numbers With And Without Using Third Variable
Program To Demonstrate How To Run A Simple Applet In Java