Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

Table of Contents

What is Garbage Collection in Java

Garbage collection Is an essential process in programming which allows you to write efficient codes. Java is no exception to this development practice, but did you know Java doesn’t allow you to perform Garbage Collection? Or it takes care of the collection process by itself? If you are wondering how a programming language can be capable of doing so, this blog is for you.  

According to Statista, Java is used by about 30 per cent of developers worldwide. Java’s ability to automate Garbage Collection is one of the reasons for its immense popularity worldwide. This blog on Garbage Collection will dive into what is Garbage Collection in Java, how it works and why Java Garbage Collection is so important. Continue reading to learn more!

Table of Contents

1) Understanding Garbage Collection in Java

2) How does Java Garbage Collection work?

3) What are the different types of Garbage Collectors?

4) Java Garbage Collection methods

5) Advantages of Garbage Collection in Java

6) Conclusion

Understanding Garbage Collection in Java

Garbage Collection is a crucial aspect of Java's automatic memory management system. In other languages like C and C++, programmers must manually create and destroy objects. However, Java automates this process to prevent memory-related issues.

In C and C++, overlooking object destruction can lead to "memory leaks." These leaks cause a continuous growth in memory usage, eventually leading to "OutOfMemoryErrors" and program termination.

In these languages, developers use functions like "free()" in C and "delete()" in C++ for Garbage Collection. However, in Java, this process occurs automatically during a program's execution, eliminating the need for manual memory deallocation and ensuring memory leaks are avoided.

Java Garbage Collection functions when Java programs run on the Java Virtual Machine (JVM). Objects created during a program's lifetime reside in an allocated portion of memory known as the heap.

As the program progresses, new objects are created, and others become obsolete. These objects fall into two categories within the heap:

a) Live objects: Actively in use and referenced elsewhere in the program.

b) Dead objects: No longer needed or referenced.

The Garbage Collector identifies and removes these dead objects, releasing memory for efficient use. This automated process allows Java Developers to focus on writing code rather than managing memory, contributing to Java's reliability and ease of use.
 

JAVA Training
 

How does Java Garbage Collection work?

As a programmer, you are responsible for both an object's creation and destruction. You are expected to remove an object, similar to how you declare them in most programs. Failing to do so would often result in the message “OutOfMemoryErrors” being thrown by your compiler. In such a scenario, Java’s GC feature shines brightly by automating object destruction.  

Java’s GC feature is a blessing to programmers, allowing you to focus on your main goal instead. Java runs its program by converting them into Bytecodes, which are then interpreted by Java Virtual Machine. Any object created is stored in a heap memory, which JVM dedicates to storing data.    

GC ensures this heap has free space by deleting any unnecessary object; hence, they are called “Garbage” in the program. An object that is categorised as so if it is considered an “unreachable object”. Any present thread within a program cannot access this object. But you must be wondering how JVM can categorise an object as unreachable. It does so while considering certain factors, such as the generation of objects in the collection process. 

Learn to build applications from scratch with our Introduction to Java EE Training – Sign up today!

Object Generations in Java

  Object Generations in Java

Java GC follows a generational strategy, allowing it to categorise objects by age. Most objects in a program have a relatively short life span, allowing them to get categorised as Garbage objects. The generation of Java objects in the Garbage Collection is as follows. 

1) The Young Generation objects: A freshly created object starts by being categorised into the Young Generation. This generation is divided into three parts and two categories: one Eden space and two survivor spaces. A newly declared object is stored in Eden space. When an object has survived Garbage Collection for the first time, it gets moved to the survivor space. Collection in the Young Generation is also called a minor Garbage Collection event. 

2) The Old Generation objects: When an object has lived long enough in the Young Generation, GC will move it into the Old Generation category. Collection in Old Generation is referred to as a major Garbage Collection event. 

3) The Permanent Generation objects: All forms of metadata, such as methods and classes, are stored in the Permanent Generation. JVM collects any class or method with no further use from Permanent Generation. Alternatively, when JVM performs a full Garbage Collection, all unused objects are collected irrelevant of their generation.

What are the different types of Garbage Collectors?

Java provides a spectrum of Garbage Collectors, each meticulously designed to cater to distinct application demands. Let's take a look at some of these Garbage Collectors:

1) Serial Garbage Collector: As Java's default collector, it suits small to medium-sized applications with modest throughput requirements. It functions efficiently, minimising the occurrence of disruptive "stop the world" events. However, it may not be the ideal choice for applications with stringent performance demands. 

2) Parallel Garbage Collector: This collector is engineered for high-throughput applications, particularly those dealing with extensive memory heaps. Leveraging multiple CPU cores accelerates the Garbage Collection process. But there's a trade-off – it temporarily freezes application threads during Garbage Collection, which may not be acceptable for applications with stringent responsiveness requirements. 

3) Concurrent Mark Sweep (CMS) Collector: Ideal for applications that demand minimal pause times. It excels in scenarios with numerous live objects and strives to keep pauses short. However, its performance can degrade under heavy memory pressure, making it essential to monitor closely. 

4) G1 Garbage Collector: Tailored for large memory heaps, the G1 Garbage Collector adeptly manages a mix of short and long-lived objects. It uses multiple threads for concurrent heap scanning and compaction. G1 offers a balanced approach, aiming to minimise both pause times and overall Garbage Collection overhead. 

Selecting the right Garbage Collector depends on a thorough understanding of your application's specific needs. Furthermore, you can fine-tune collector settings to optimise performance, ensuring your Java application runs smoothly even under varying workloads.

Become a Java expert with our Java Engineer Training – Sign up today

Java Garbage Collection methods 

GC in JVM works automatically and doesn’t require you to delete an object once its scope is finished manually. However, the conditions necessary to trigger GC can be triggered by a programmer, including invoking GC and qualifying objects. 

Dereferencing objects  

GC primarily targets objects for cleanup when they are dereferenced. There are certain methods to dereference an object within a Java program, and some common methods of dereferencing objects are as follows. 

1) Assign null value: This can be done by allotting a null value to a previously declared object. By setting the reference value of an object to null, you’ll dereference it. As the example below shows, using the null keyword as a reference value to your object myString has dereferenced it. 
 

public class ObjectDemo
{
public static void main(String[] args)
{
// Create a new object of the String class
String myString = new String("Hello World");
// Output the string before it is dereferenced
System.out.println("Before dereferencing: " + myString);
// Set the reference variable to null to dereference the object myString = null;
// Output the string after it is dereferenced
System.out.println("After dereferencing: " + myString);
}
}


Output: 

Before dereferencing: Hello World 
After dereferencing: null 

2) Assign value to another object: This can be done by reassigning the value of an object to another object. This makes the previous object dereferenced, thus qualifying for the Garbage Collection process. 

Program: 
 

public class Main
{
public static void main(String[] args)
{
// create a new Person object
Person person1 = new Person("John", 25);
// assign the reference value of person1 to person2 Person person2 = person1;
// assign null to person1, dereferencing the object it referred to person1 = null;
// print the name of person2 (which still refers to the object)
// and print person1 (which is null)
System.out.println("Person 2 name: " + person2.getName());
System.out.println("Person 1 is null: " + (person1 == null));
}
}
class Person {
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
}


Output: 

Person 2 name: John 
Person 1 is null: true 

3) Assign no value to the object: Lastly, you can allot no reference value to an object, known as an anonymous object. Below is a program to print an anonymous object in Java and prove it is dereferenced. 

Program: 
 

public static void main(String[] args)
{
// Declare an anonymous object of the Person class Person p = new Person("John", 25);
// Print the details of the anonymous object
System.out.println("Name: " + p.name);
System.out.println("Age: " + p.age);
// Dereference the anonymous object p = null;
// Try printing details of the anonymous object
// This will result in a NullPointerException
//because the object has been dereferenced
System.out.println("Name: " + p.name);
System.out.println("Age: " + p.age);
}
}
class Person
{
String name;
int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
}


Output: 

Name: John 
Age: 25 
Exception in thread "main" java.lang.NullPointerException 
at AnonymousObjectDemo.main(source.java:15) 

Garbage Collection Methods 

A dereferenced object makes it a valid candidate for Garbage Collection, but it doesn’t promise that JVM will make GC act upon it. Here are specific methods to trigger the GC within a Java program. 

1) gc() Garbage Collection method: It’s used to initiate a cleaning process within a program. This method is found in runtime and system classes and acts as a signal to the GC. You are not required to call GC manually, as JVM performs this automatically. However, this code proves it is possible to do so manually. Below is a Java program using the gc() method for collecting dereferenced objects. 

Program: 
 

public class GarbageCollectionExample
{
public static void main(String[] args)
{
// Create an object
Object obj = new Object();
// Set obj to null to make it eligible for GC obj = null;
// Call garbage collector to free up memory System.gc();
// Output message to indicate when garbage collection is done System.out.println("Garbage collector has run");
}
}


Output: 

Garbage collector has run 

2) finalize() Garbage Collection method: This method is used every time before a collection process to perform some cleanup operations. This method is defined within the object class. It's important to note that the GC process is still automated in Java. This means there is no guarantee the JVM will collect an object. Below is an example of a program which uses finalize() method in GC.   

Program:   
 

public class GarbageCollector
{
public static void main(String[] args)
{
GarbageCollector obj1 = new GarbageCollector();
GarbageCollector obj2 = new GarbageCollector();
obj1 = null;
obj2 = null;
// Run the garbage collector System.gc();
}
// Override the finalize() method to perform cleanup operations @Override protected void finalize() throws Throwable
{
System.out.println("Object is being garbage collected");
// Perform some cleanup operations here // ... }
}


Output: 

Object is being garbage collected 
Object is being garbage collected 

Learn to develop your first web application with Web Development using Java Training course! 

Advantages of Garbage Collection in Java 

Java’s automatic memory management feature gives it an edge over older languages. For example, languages such as C and C++ require you to include GC methods in your code, leading to lengthy codes on a large scale, which are more liable to errors.   

Your code becomes more liable to memory-based errors without good development practices. This concern is completely removed in Java as JVM automatically categorises objects as Garbage and collects them once their scope is finished. This makes your code more memory efficient and less verbose, which matters greatly in Java as it is already considered a verbose language.   

However, automatic Garbage Collection has its vices, with its virtues. Many developers love to have control over the most minimal process in development. This includes control of memory management, which allows them to change the performance based on their needs. While Java takes away the manual work necessary for object deletion, it also takes away the freedom of control.   

Java allows you to fine-tune the GC, which can increase its efficiency. However, many developers would still opt out for a language that allows them to manage memory and object manually. 

Conclusion 

GC is an important aspect of programming that gives developers great ease thanks to its automated memory management. We hope after reading this blog, you were more informed about Garbage Collection in Java. You will also better grasp generations of objects in heap memory and their scope. Lastly, you will be more familiar with methods used to invoke Java Garbage Collection. Thank you for reading. 

Wish to learn more? Try Java Programming And Software Engineering Fundamentals Training.

Frequently Asked Questions

How can you minimise prolonged Garbage Collection in Java? faq-arrow

To mitigate long Garbage Collection pauses, consider optimising your code for memory efficiency. Use appropriate data structures, limit object creation, and fine-tune Garbage Collector settings for your application's needs. 

What are the primary factors contributing to heightened Garbage Collection activity? faq-arrow

High Garbage Collection can result from excessive object creation, memory leaks, or inefficient data structures. Frequent Garbage Collection pauses can impact application performance, so it's crucial to identify and address the underlying causes.

What are the other resources provided by The Knowledge Academy? faq-arrow

The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.

Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. By tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.
 

What is the Knowledge Pass, and how does it work? faq-arrow

The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.

What are related courses and blogs provided by The Knowledge Academy? faq-arrow

The Knowledge Academy offers various Java Courses, including Java Programming Course, JavaScript for Beginners and Java Engineer Training. These courses cater to different skill levels, providing comprehensive insights into Java Methodologies.

Our Programming & DevOps Blogs cover a range of topics related to Java, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Java Programming skills, The Knowledge Academy's diverse courses and informative blogs have you covered.
 

Upcoming Programming & DevOps Resources Batches & Dates

Date

building Java Programming

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross

OUR BIGGEST SPRING SALE!

Special Discounts

red-starWHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.