How to Make Objects Eligible for Garbage Collection in Java

Are you tired of managing memory manually in your code?

Memory management is tricky. Failing to manage memory effectively makes code error-prone and inefficient. Seemingly perfect code may run into performance issues because of inefficient memory management.

Programmers who adopt bad practices suffer from violations of memory safety and memory leaks. Operations like Garbage Collection (GC) help us recycle unused memory and manage it effectively. In Java, garbage collection allows programmers to recycle unused memory automatically.

However, garbage collection has some limitations. You see, garbage collection is only available for unreachable objects. This means only objects without reference variables are eligible for GC.

Unused objects are the greatest cause behind memory leaks. Therefore, resolving this issue is essential for programmers.

In this article, I will explain how you can make objects eligible for garbage collection in Java.

What Are Reference Variables?

Understanding what reference variables are and how referencing works in Java is essential.

As a Java developer, you may know that every Java object is assigned to a block of memory from the available heap.

Whenever you create an object in memory through the ‘new’ operator, you assign it to a reference variable. This reference variable is the variable that saves the address of the newly created object.

Human Person1 = new Human() ; // Person1 is the reference variable for the object in this code

Why Are Unreachable Objects Eligible for Garbage Collection?

You see, when objects don’t have a reference variable, they don’t have a reference in the memory heap. Therefore, these objects aren’t accessible and don’t add any value.

This happens when we create objects in the scope of a method. During program execution, methods and other components of your code are pushed to a program stack where the compiler runs them.

Whenever these methods are called, the compiler pushes objects to the program stack. Now, after execution, the program pops the method and removes it from the stack. As a result, all the elements within the method, including reference variables, die alongside the method.

However, even when the reference variables no longer exist on the program stack, the memory heap will still save unreferenced objects. Since these objects lack any reference, the JVM considers them anonymous objects.

As a result, it automatically recycles them through garbage collection. We will explain what anonymous objects are later in the article.

class Example1{// this variable is created to store an object called name1String obj1;public Example1(String obj1){this.obj1 = obj1;}static void show(){//object test_case1 inside the method becomes unreachable when show() is removedExample1 test_case1 = new Example1(“test_case1”);display();}static void display(){//object test_case2 inside the method becomes unreachable when display() is removedExample1 test_case2 = new Example1(“test_case2”);}// Driver methodpublic static void main(String args[]){// calling show()show();// calling garbage collectorSystem.gc();}@Override/* We are using Override to show which object the garbage collector is collecting*/protected void finalize() throws Throwable{// this line will print the name of the object that has been garbage collected successfullySystem.out.println(this.obj1 + “ successfully garbage collected”);}}

Both objects here have become unreachable after program execution. Understandably, they print the following outcome:

test_case2 successfully garbage collectedtest_case1 successfully garbage collected

This shows that once an object within the method is useless, it automatically becomes eligible for garbage collection.

3 Ways to Make Objects Eligible for Garbage Collection in Java

You can make objects eligible for garbage collection in Java by the following three techniques.

Reassigning Reference Variables

Understanding what reference variables are and how referencing works in Java is essential. As a Java developer, you may know that every Java object is assigned to a block of memory from the available heap.

Whenever you create an object in memory through the ‘new’ operator, you assign it to a reference variable. This reference variable is the variable that saves the address of the newly created object.

 class Example2{// this line of code stores the object nameString obj1;public Example2(String obj1){this.obj1 = obj1;}// Main methodpublic static void main(String args[]){Example2 test_case1 = new Example2(“test_case1”);Example2 test_case2 = new Example2(“test_case2”);//test_case1 now refers to test_case2test_case1 = test_case2;// this line of code is used to call the garbage collectorSystem.gc();}@Override/* Overriding to check which of the two objects are being garbage collected */protected void finalize() throws Throwable{// this line of code prints out the name of the object that has been garbage collectedSystem.out.println(this.obj1 + “ has been garbage collected successfully”);}}

Assigning the reference variable of the object test_case1 to reference the test_case2 makes test_case1 eligible for garbage collection. The output of this code will be:

test_case1 has been garbage collected successfully

Nullified Reference Variables

You can also make objects eligible for garbage collection by making the reference variable equal to NULL. Doing so disconnects the object with the reference variable, making it unreachable. Once the object becomes unreachable, you can use the garbage collector to remove it from the memory heap.

The following code shows how nullifying the reference variable enables the garbage collector to recycle the object automatically:

/* This code shows how garbage collection works when we assign NULL to the reference variable*/class Example3{// this line of code is used to store the name of the objectString obj1;public Example3(String obj1){this.obj1 = obj1;}// Mainpublic static void main(String args[]){Example3 test_case1 = new Example3(“test_case1”);/* When test_case1 is no longer needed, the object that refers to it can be changed to NULL for garbage collection*/test_case1 = null;// garbage collector is called with this line of codeSystem.gc();}@Override/*We are using Override to show which method the garbage collector is collecting*/protected void finalize() throws Throwable{// will print the name of the objectSystem.out.println(“ Garbage Collector successfully collected “ +this.obj1);}}

You can see test_case1 no longer has a reference variable after it was declared NULL. As a result, the object is successfully removed by the garbage collector and the output for test_case1 is:

Garbage Collector successfully collected test_case1

Anonymous Objects

Anonymous objects or nameless objects are special objects in Java that don’t need a reference variable. Usually, when we declare objects in Java, we declare them through reference variables, such as:

Cards card1 = new Cards() //creating a regular object

However, you don’t need reference variables to create anonymous objects. This makes anonymous objects excellent for methods and classes that only need one object. Imagine building an array of a deck of 52 cards with each card being an object of the Class Cards.

Using reference variables means declaring the Cards object 52 times and then use the add() method to add each of them to the array.

In contrast, an anonymous object allows you to create objects directly inside the add() method. This means you can perform the same operation in fewer lines of code. Plus, they are automatically eligible for garbage collection.

Array1.add(new Cards() ) //creating an anonymous object

Let us see another example of how anonymous objects work:

public class Example4 {public String test(){return “This is an example”;}public static void main(String[] args) {System.out.println(new Example4().test());// here, we are using the test() method on the anonymous object Example4()}}The output of the code above will be as follows:This is an exampleNow let us see how we can use garbage collection to remove anonymous objects from the memory heap.class Example4{// this line of code is used to store the name of the objectString obj1;public Example4(String obj1){this.obj1 = obj1;}// Main methodpublic static void main(String args[]){//this is how an anonymous object without a reference ID is being instantiatednew Example4(“test_case1”);// this line of code is being used to call the garbage collector to remove the anonymous objectSystem.gc();}@Override/* We are using Override to show which object the garbage collector is collecting*/protected void finalize() throws Throwable{// this line of code will print the name of the object that is being garbage collectedSystem.out.println(“ Garbage Collector successfully collected “ + this.obj1);}}

In the absence of a reference variable, the garbage collector will easily remove the anonymous object from the heap:

Garbage Collector successfully collected test_case1

Good memory management is an essential part of writing efficient and sustainable code. Garbage collection in Java helps recycle memory automatically. By using the techniques above, you can optimize your code by leveraging garbage collection more effectively.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How To Escape Tutorial Hell As A Developer

My experience with 30 Days of Web Development

Leetcode : 362. Design Hit Counter

Sanitise your System Dumps !

Docker + maven build problem — unix://localhost:80: Permission denied

Automating Terraform Policy Enforcement with Sentinel and ServiceNow

KDAG Monthly Update | September 1–30, 2021

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Muhammad Fasih Khan

Muhammad Fasih Khan

More from Medium

Java Reactive Programming: Something Old, Something New

Mixins — Multiple Inheritance in Java

Better code in Java using VAVR

What, when, how, why, advantage, and disadvantage of java @Annotations