What is Garbage Collector and How it works in Java with example

Like any other programming language, java programs too needs some memory to perform its operations. The memory is divided in a number of regions like Stack, Heap , Method Area .. etc.

All Java objects live and die in Heap Memory and this is the only part of memory where Garbage Collector performs its operations.

What exactly the garbage collector does in Java ?

We know that all the objects in java resides on Heap, each object occupies some space when its created and hence we need to ensure that heap is not running out of memory before creating a new object. This is what garbage collector does exactly, it checks for objects that are not having any reference and removes them from the memory so that enough space can be created for new objects.

How and When garbage collector checks for un-reachable object to remove them from memory is totally dependent on JVM itself and can not be controlled by the program. There are few ways to request JVM to run garbage collector for performing removal activity but it?s totally upon JVM to accept your request at the moment you requested, or it can delay the process for some other time.

How garbage collector identifies un-reachable objects ?

In java we can write multithreaded programs, where program execution is divided into multiple threads and each thread executes in its own stack. Even if we don?t create new threads there is always a thread running called main, so every Java program has at least one running thread for sure.

So by theory, an object is considered as a non-reachable object if no live thread is accessing that object. Meaning that if an object is pointed by a reference variable and that reference variable is accessed or used by some live thread than the object is called reachable object.

When does a Java program throw out of memory ?

So garbage collector is responsible to free the heap memory by removing un-reachable objects that are no longer in use by the current live threads. But, sometime a situation may arise when we have a number of running objects and all of them are reachable by the program, in that case no object can be removed from the Heap to make the memory free for new object creation. This is when Heap is full with reachable objects and the program tries to create a new object on heap, because of no memory available for new object creation we got a out of memory exception.

Lets see and example, to demonstrate what does garbage collection eligibility means:

StringBuffer s1 = new StringBuffer("Tech");
StringBuffer s2 = new StringBuffer("Burps");

In above two lines, two variables are created s1 and s2 and two new object are also created with values ?Tech? and ?Burps?. Object ?Tech? is pointed by s1 and ?Burps? is pointed by s2 so these two are not eligible for garbage collection. No see the lines below:

s1 = s2;

Now we have one more assignment, we just pointed s1 to point object that is previously referenced by s1.

Here s1 and S2 both are referencing to single object ?Tech? and the object ?Burps? is not referenced by any variable hence ?Burps? is eligible for garbage collection.

All the objects that are created in methods are eligible for garbage collection once the method execution is done and method returns. See the example below:

	public int printValue(){
		StringBuffer s1 = new StringBuffer("Tech");
		return s1.length();

In method printValue(), a object is created with value ?Tech? and as soon as the method returns length of the string lateral s1 is turns to be eligible for garbage collection.

But there are few exceptions, if a method is returning a created object and the object is referenced by some variable in caller method than the method is not eligible for garbage collection. See example below:

public StringBuffer getValue() {
		StringBuffer s1 = new StringBuffer("Tech");
		return s1;

public void printValue() {
		StringBuffer buffer = getValue();

In the code above although getValue() is done with returning value, but ?Tech? object is now referenced by buffer variable in printValue() method so ?Tech? is not eligible for garbage collection.

Make JVM to run Garbage Collector

Theoretically, there are few ways to suggest or request JVM to run garbage collector, but this is totally dependent in JVM to grant your request or deny. JVM has a special class ?Runtime? this class is the only way to communicate with JVM from the program. Runtime class has a singleton class and this singleton instance can be obtained using getRuntime() method. We can call gc() in this instance to request JVM to run garbage collector:

		Runtime runtime = Runtime.getRuntime();

Or alternatively, you can call gc() on System class, as shown below:

Theoretically, after running System.gc(); You will get as much free memory as possible, by experiments its proved that JVM grants gc() request most of the time. So something is better than nothing, that?s why we use System.gc(); when we need to make JVM run garbage collector.

What is finalize() method in Java?

Method, finalize() is a part of mechanism that gives objects a final chance to run some code before the object is deleted from the memory. This is useful when you want to free some resources that is dependent on the garbage collectable object. But again there is no guarantee if the code written in overridden finalize() method runs or not. The finalize() method can be overridden like:

class Car {
	protected void finalize() throws Throwable {
		// / code to run before garbage collection

In this article we saw, What is Garbage Collector in Java, How garbage collector works and how to make JVM run garbage collector from program code. In upcoming articles we will see more about Java and other open source technologies.

About The Author

Nagesh Chauhan

Nagesh Chauhan has 8+ years of software design and development experience in variety of technologies like - Core Java, Java 8 (Streams, Lambda), J2EE (Servlet, JSP), Spring Framework (MVC, IOC, JDBC, SECURITY etc), Spring Boot and Microservices, Kafla, Redis, Cassandra and Spark.