Optimizing Your Java Code with Garbage Collection: A Step-by-Step Guide

Optimizing Your Java Code with Garbage Collection: A Step-by-Step Guide

6 mins read356 Views Comment
Updated on Oct 3, 2023 11:48 IST

In this article, we will discuss what is garbage collection in java, how to make an object eligible for a garbage collector, and different methods that can be used to make JVM to run garbage collector to collect unreferenced objects or garbage for better performance of the program.

2023_01_MicrosoftTeams-image-160.jpg

Introduction

In older programming languages ​​like C++, programmers are responsible for both creating and destroying objects. Usually, programmers are very careful when creating objects and neglect to dispose of useless objects. Due to that carelessness, at some point, not enough memory will be available to create new objects, and the entire application may shut down due to out-of-memory issues. So OutofMemoryError is a very common problem in older languages ​​like C++.
But in Java, the programmer is only responsible for creating objects, not for destroying unwanted objects. In Java, dead objects are called garbage, and a garbage collector is always running in the background to destroy dead objects. Just having this garbage collector makes it very unlikely that your Java program will fail. This is also the reason for Java’s robustness. Therefore, the main purpose of the garbage collector is to dispose of unneeded objects. The process by which the garbage collector discards unnecessary objects is called garbage collection. A daemon thread that runs in the background all the time is the best example of a garbage collector.
It is strongly recommended that objects be eligible for garbage collection when they are no longer needed. If an object has no references, it is considered eligible for garbage collection.

Must Check: What is Java?

Must Check: Top Java Online Courses & Certifications

Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
6 weeks
15 K
3 months
2.05 K
3 months
– / –
170 hours
5.4 K
1 month
– / –
6 months
– / –
2 months
17 K
3 months
5.5 K
1 month

What is Garbage means in Java?

Garbage means any unreferenced object which is no longer in use and occupying memory in a heap.

Advantages of Garbage collection

  • Increase the program performance by destroying objects which are occupying space in heap memory.
  • Proper memory management is possible due to the automatic deallocation of unreferenced objects.
  • It gives relief to the programmer from the burden of freeing allocated memory.

Ways to make an object eligible for Garbage Collection

Even though the programmer is not responsible for destroying useless objects but it is highly recommended to make an object eligible for Garbage Collector if that object is no longer needed. An object is said to be eligible for Garbage Collector if that object has no reference. These are the ways by which we make an object eligible for Garbage Collector.

  1. Nullifying the Reference variable
  2. Re Assigning the Reference variable
  3. Object created inside a method

Nullifying the Reference variable

In the program, if an object is no longer in use, then we should assign null to its reference variable to make that object eligible for the garbage collector. Let’s observe the below code to understand this clearly.
Code:

 
public class Team{
public static void main(String args[]) {
//Reference variable football is assigned with new Team() object
Team football =new Team();
// Nullifying reference variable football
football=null;
}
}
Copy code

In the above code, We create an object(new Team() ) of the Team class and assign it to its reference variable, football. To make this object eligible for Garbage collector, we assign a null value to the reference variable football.

Re Assigning the Reference Variable

In the program, if an object is no longer in use, then we can make its reference variable point out to another object so that it is eligible for Garbage collector. Let’s understand this scenario with the below code.
Code

 
public class Team{
public static void main(String args[]) {
//Reference variable football is assigned with Team object
Team football =new Team();
//Reference variable cricket is assigned with Team object
Team cricket =new Team();
// both reference variable cricket and football pointing to one object and other is eligible for garbage collector
cricket=football;
}
}
Copy code

In the above code, we create a reference variable, football, assigned to an object, and a reference variable, cricket, is assigned to another object. To make an object eligible for Garbage collector, we re-assign the reference variable football to another object.

Object created inside a method

In the program, if the object is created inside the method, then automatically it is eligible for garbage collector because the reference variable of the object is no longer pointing to the object as the reference variable is local to the method and after completion of execution of this method reference variable is no longer pointing. Let’s observe the below code two understand this scenario.
Code

 
public class Team{
public static void match() {
// create an object and assign it to reference variable football
Team football =new Team();
// create an object and assign it to reference variable cricket
Team cricket=new Team();
}
public static void main(String args[]) {
// calling match method
match();
}
}
Copy code

In the above code, we create a static method match and create two objects inside the method. Reference variables football and cricket are pointing to the respective objects. Inside the main method, we call the match method, so after the execution of the match method completes, those two reference variables are no longer pointing to respective objects. Hence, two objects are eligible for the garbage collector.

Ways for requesting JVM to run a Garbage Collector

Once we make an object eligible for garbage collector by any of the ways we discussed, then that object is not immediately destroyed by the garbage collector. It depends on the JVM to run the garbage collector then; only that object will destroy. So, we don’t know at which time JVM runs the garbage collector; it varies from JVM to JVM. Thus, to resolve the issue of undefined time to run the garbage collector by JVM, we can request JVM to run the garbage collector in two ways.

  1. By using the System class 
  2. By using the Runtime class

Before we understand the above two ways of using the program, let us first we understand what is finalize() method.

What is finalize() method?

In Java, whenever an object is a garbage collected by a garbage collector, then prior to this finalize() method is invoked to do cleanup processing. We defined finalize method as follows:

 
public void finalize() {
// codes
}
Copy code

By using the System class

The system class contains a static method gc() which requests JVM to run the garbage collector. Observe the below program to understand this scenario.
Program:

 
public class Team{
// finalize() method called each time prior to garbage collected by garbage collector
public void finalize() {
System.out.println(" object is collected by Garbage collector");
}
public static void main(String args[]) {
//Reference variable football is assigned with new Team() object
Team football =new Team();
// Nullifying reference variable football
football=null;
// static method gc() request JVM to run garbage collector
System.gc();
}
}
Copy code

Output:

2023_01_image-149.jpg

By using Runtime class

We need a Runtime object to make communication between our java application and JVM. Runtime class is present in Java.lang package, and it is a singleton class. We can create a Runtime object by using Runtime.getRuntime() method; see the below syntax to understand it.

Runtime runtime_Reference= Runtime.getRuntime();

Once we get the Runtime object then, we can call the following methods on that object

  1. totalMemory() : It returns a number of bytes of total memory present on the heap (heap size).
  2. freeMemory() : It returns a number of bytes of free memory present in a heap.
  3. gc() : For requesting JVM to run the garbage collector

Let’s observe the below program and understand how to use the Runtime class.

Program

 
public class Team{
//finalize() method call prior to garbage collected by garbage collector
protected void finalize() {
System.out.println("Object is destroy");
}
public static void main(String args[]) {
// Creating Runtime object
Runtime runtime_reference= Runtime.getRuntime();
//creating Team object
Team football=new Team();
football=null;
//Total memory in heap
System.out.println("Total Memory: "+ runtime_reference.totalMemory());
// Free memory in heap
System.out.println("Free Memory when object is eligible for garbage collector: "+ runtime_reference.freeMemory());
// Runtime refrence calling gc() which request JVM to run garbage collector
runtime_reference.gc();
System.out.println("garbage collector collected unrefernced object");
//Free memory in heap
System.out.println("Free Memory when garbage collector collected garbage: "+ runtime_reference.freeMemory());
}
}
Copy code

Output

2023_01_image-150.jpg

In the output, we observe that when the object is created and eligible for the garbage collector, that time free memory is 111062304 bytes in a heap, and when the garbage collector collects the unreferenced object and cleanup is done by finalize() method, then the free memory in a heap is increase to 112351928 bytes.

Conclusion

In this article, we have discussed what is garbage collection in java, how to make an object eligible for garbage collector and different methods that can be used to make JVM to run garbage collector to collect unreferenced objects or garbage.

Hope, you will like the article.

Contributed By: Shubham Kumar

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio