top of page

Welcome
to NumpyNinja Blogs

NumpyNinja: Blogs. Demystifying Tech,

One Blog at a Time.
Millions of views. 

Java Garbage Collection

Apr 29, 2025
6 min read

Have you ever wondered how you are going to deal with memory management in your java code? Nope; you haven’t ! Thanks to java’s garbage collector that provides an automatic solution to memory management. We will go through the basics of what java does behind the scenes to manage memory so you don’t have to.  


Memory management is an important aspect while developing an application. Imagine you need to read a large amount of data in your application from an external data source and write the data into a database on a hard drive. A typical design would be to read the data into some sort of collections and perform some operations on the data and then write the data into the database. Then the collection that stored the data temporarily must be emptied of old data or deleted and recreated before processing the next batch of data. This process is repeated thousands of times and in languages like C and C++ that do not offer automatic garbage collection, a small flaw in the code that empties or deletes the collection data might end up in a small amount of data in memory being reclaimed improperly or lost forever. These small losses are called Memory Leaks and over many thousands of iterations, they can make enough memory inaccessible and the program crashes eventually. This is where java’s garbage collector plays a crucial role, it frees you from having to add any memory management code in your application and hence avoids memory leaks. 


Overview of Garbage Collection

In java, all the objects live in the part of the memory called heap and it is the only part of the memory that is garbage collectable. When garbage collector runs, it looks for the objects in the heap that can’t be reached anymore and deletes them from the memory. Thus it makes sure the heap has as much free space as possible.


So when does the garbage collector run? It’s totally up to the JVM! It will run the collector when it senses that the memory is running low. From within your program, you can ask the JVM to run it, JVM will usually grant your request in short order, but there are no guarantees. 


How to make an object eligible for collection?

As mentioned earlier, an object is eligible for garbage collection when there are no more reachable references to it. There are different ways to do it

  1. Nulling a Reference

  The first way to remove a reference to an object is to set the reference variable that refers to the object to null


Here is an example:

public class GarbageTruck {

public static void main ( String[] args) {

StringBuffer sb = new StringBuffer(“hello”);

System.out.println(sb);

//  The StringBuffer object is not eligible for garbage collection as the variable sb is referring to it. 

sb = null;

// Now the StringBuffer object is eligible for collection

}

}


In line no 3, the StringBuffer object with value “hello” is assigned to the reference variable sb. But when we set the variable to null in line no 6, it removes the only reference existed to the object


  1. Creating Object Reference within a Method

Objects that are created in a method exist only for the duration of that method. Once the method has returned, the objects are eligible for garbage collection. Take a look at this example:

public class Animals {

public static void main ( String[] args) {

doCatStuff();

System.out.println(“I am done doing cat stuff”); 

}

public static void doCatStuff() {

Cat myCat = new Cat();

myCat.meow();

}

}

Here the object myCat is accessible only within the method doCatStuff(). Once the method has returned, myCat object is eligible for collection. But if an object is returned from the method, its reference might be assigned to a reference variable in the method that called it; hence, it will not be eligible for collection.

public class Animals {

public static void main ( String[] args) {

Cat cat = doCatStuff();

// cat object is still being used; not ready for garbage collection

System.out.println(cat.meow());  

}

public static Cat doCatStuff() {

Cat myCat = new Cat();

myCat.meow();

return myCat ;

}

}


  1. Reassigning a Reference Variable

We can decouple a reference variable from an object by setting the variable to refer to another object. 

Example:

public class GarbageTruck {

public static void main ( String[] args) {

StringBuffer s1 = new StringBuffer(“hello”);

StringBuffer s2 = new StringBuffer(“hi”);

//  At this point both objects are being referred by variables s1 and s2 

System.out.println(s1); // Prints hello

s1 = s2; // now both s1 and s2 are referring to the object “hi” and no reference to “hello”. So the object is ready for garbage collection


}

}


  1. Isolating a Reference

There is another way in which objects can become eligible for garbage collection, even if they still have valid references! We call this scenario “islands of isolation.” For example, imagine a class that has an instance variable that is a reference variable to another instance of the same class. Now imagine that two such instances exist and that they refer to each other. If all other references to these two objects are removed,there will be no way for any live thread to access either object. When the garbage collector runs, it can usually discover any such islands of objects and remove them. Examine the following code:


Here the island objects t1,t2, and t3 have instance variables so that they can refer to each other, but their links to the outside world have been nulled. Now these objects are eligible for garbage collection.


Forcing Garbage Collection

As you know by now, garbage collection cannot be forced. However, Java provides some methods that allow you to request that the JVM perform garbage collection.The garbage collection routines that Java provides are members of the Runtime class. This class provides a mechanism for communicating directly with the virtual machine. To get the Runtime instance, you can use the method Runtime.getRuntime(), which returns the Singleton object of the class(one single object per main program). Using this runtime object, you can invoke the garbage collector using the gc() method.

public class CheckGarbageCollector{

public static void main ( String[] args) {

Runtime rt = Runtime.getRuntime();

Date d= null;

for(int i = 0;i<10000;i++) {

d= new Date();

d= null;

}

rt.gc(); // calling garbage collector

}

}


 Alternatively, you can call the same method on the System class, which has static methods. The simplest way to ask for garbage collection (remember—just a request) is

System.gc();


Cleaning up before Garbage Collection using finalize() method

Java provides a way to execute some cleanup code before your object is deleted by the garbage collector. It is written in the finalize() method which belongs to the Object class and you can override the method in your class. If your object opened up some resources, you can write code to close them in the finalize method. But again, the problem is that you can’t count on the garbage collector to delete the object and hence there is no guarantee that the finalize method will ever get executed. The two important things about finalize method are:

  • It will be executed only once (at most) by the collector for a given object

  • You can save an object from deletion using finalize method

You can put any code in the finalize method that you would put in a regular method. For example you can write code that passes a reference to the object in question back to another object, effectively ineligible-izing the object for garbage collection. If at some later point this same object becomes eligible for garbage collection again, the garbage collector can still process the object and delete it. 


Summary

To summarize, java does automatic memory management using garbage collection. It manages memory by deleting objects that are not reachable  from the heap . There are different ways to make an object eligible for garbage collection like nulling a reference,creating object reference within a method, reassigning a reference variable and islationg a reference. There are ways to invoke garbage collector like System.gc() and RuntimeObject.gc(). But there is no guarantee that it will get executed; It's totally up to the garbage collector when to run it. Also you can make use of the finalize() method to execute cleanup code before the object is deleted.


 
 

+1 (302) 200-8320

NumPy_Ninja_Logo (1).png

Numpy Ninja Inc. 8 The Grn Ste A Dover, DE 19901

© Copyright 2025 by Numpy Ninja Inc.

  • Twitter
  • LinkedIn
bottom of page