Garbage Collection in Java

The Java garbage collector is a process that automatically manages memory for Java programs. Objects are created in memory when a program runs on the Java Virtual Machine (JVM). Eventually, some of these objects are unnecessary and take up space unnecessarily.

The garbage collector (Java GC) helps identify these unused objects and remove them to make more memory available for the program.

Post On:Garbage Collection in Java
Post Type:Java Tutorials
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:SoftwareTestingo Telegram Group

There are many different opinions on garbage collection:

  • Whether it is good or bad?
  • When is it needed?
  • How often should it run?
  • How do you tune the garbage collection operation?
  • Knowing when it is not operating as expected, and so on.

In this educational post, we will try to clear up JVM garbage collection and make it easy for everyone to handle.

  • What is a Garbage Collection?
  • How Does Garbage Collector Work?
  • Why Should You Care About Garbage Collectors?

Garbage Collection in Java – What is Garbage Collection (GC)?

We know that Java applications automatically obtain objects in memory as needed. But in those memories, some memory is no longer used by any Java application. In such cases, the task of Java Garbage collection (GS) is to automatically find those unused memories in the Java virtual machine (JVM) and recycle this memory for other uses.

But in Java, the programmer does not need to care for all those objects that are no longer in use. Garbage collector destroys these objects. The main objective of the Garbage Collector is to free heap memory by destroying unreachable objects.

How does Garbage Collector work in Java?

Java garbage collection is an automatic process that doesn’t require the programmer to mark objects for deletion. Automated garbage collection looks at heap memory, identifies the unused objects in the application, and deletes those objects.

An object in use, or reference, means that some part of your program still has a pointer to that object. Any part of your program no longer references or unreferenced objects so that the garbage collector can reclaim the memory used by that object.

GC works in two simple steps, known as Mark and Sweep:

  • Mark – the garbage collector identifies the used and unused objects at this stage.
  • Sweep – this step removes objects identified during the “mark” phase.

As Java has a Garbage collection feature, the programmer does not need to explicitly mark objects to be deleted. The garbage collection implementation lives in the JVM. 

Advantages of Garbage Collection

  • Java is memory efficient because the garbage collector removes unreferenced objects from heap memory.
  • The garbage collector automatically cleans up memory, so we don’t need to do anything extra.

Disadvantages:

  • Since JVM has to keep track of object reference creation and deletion, this activity requires more CPU power than the original application. That’s why GC may affect the performance of requests that require large amounts of memory.
  • Programmers cannot control when the CPU frees up no longer-needed objects.
  • If you use certain GC implementations, your application might stop working unexpectedly.

How can an object be unreferenced?

An object can mainly be unreferenced in 3 ways, and that is:

  • By Unreachable objects Or nulling the reference
  • By Assigning a reference to Another
  • By Anonymous object, etc.

Unreachable objects Or Nulling the Reference.

We will say an object is unreachable when there is no valid reference to that object. Please note that objects part of the island of isolation are also inaccessible.

package com.softwaretestingo.basic;
public class GarbageCollectionEx1 
{
	public static void main(String[] args) 
	{
		// String object referenced by variable str thats why its not eligible for GC yet.
		String str = "Welcome to SoftwareTestingo"; 
		// String object referenced by variable str is eligible for GC.
		str = null; 
		System.out.println("str eligible for GC: " + str);
	}
}

Output:

str eligible for GC: null

In the first sentence, the String object str is reachable with the help of reference str. But when we have assigned Null to the reference, the String object becomes unreachable.

Assigning a Reference to Another

We can make a reference variable refer to another object. We decouple the reference variable from the original object by reassigning it, making it eligible for garbage collection.

package com.softwaretestingo.basic;
public class GarbageCollectionEx2 
{
	public static void main(String[] args) 
	{
		// String object referenced by variable str1 and str2 and so these are not eligible for GC yet.
		String str1 = "Welcome to Software";
		String str2 = "Welcome to Testingo"; 
		// String object referenced by variable str1 is eligible for GC.
		str1 = str2; 
	}
}

By Anonymous object

new Softwaretestingo();

Suppose we create an object without a reference variable; then that is called an Anonymous object. And can use it at the time of object creation only. And after that, it is available for Java GC.

How to Java Force Garbage Collection (Java GC)?

Once we make an object eligible for garbage collection, the GC may not immediately destroy it. The GC will only destroy the objects when the JVM runs the Garbage Collector program. However, we cannot expect when the JVM will run the Garbage Collector.

If the user wants, the user can use Java to force garbage collection or force an object to be garbage collected in Java by running Garbage Collector. We can request in two ways:

  • Using System.gc() method: A static gc() method is present inside the System and RunTime class. When invoking the gc() method, we request that JVM run Garbage Collector.
System.gc();
Runtime.getRuntime().gc();

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before the object is garbage collected.

Finalize() Method:

Before destroying any object, the Garbage collection (GC) calls the finalize() method to perform cleanup activities. Once finalize() method is completed, the Garbage Collector destroys that object. We can find the finalize() methods inside the object class.

protected void finalize() throws Throwable

Note: The Garbage collector of JVM collects only those objects created by new keywords. So, if you have created any object without a new one, you can use the finalize method to perform cleanup processing (destroying remaining objects).

Garbage Collection in Java Example

package com.SoftwareTestingo.JavaBasics;
public class GarbageCollectionEx3 
{
	public void finalize()
	{
		System.out.println("Finalize method called");
	}  
	public static void main(String[] args) 
	{
		GarbageCollectionEx3 obj1=new GarbageCollectionEx3();
		GarbageCollectionEx3 obj2=new GarbageCollectionEx3();
		
		//Objects are eligible for GC
		obj1=null;
		obj2=null;
		System.gc();
	}
}

Note: Neither finalization nor garbage collection is guaranteed.

Conclusion

Understanding Java garbage collection can help programmers find ways to increase performance in their applications. Knowing a bit about how it works and its various types is the first step toward mastering your skills as a programmer.

You might wonder why you should learn about this if you’re not programming for big tech companies like Google or Amazon.

The answer is that minor optimizations around garbage collection will make your program faster – less time waiting while files load on computers and more time doing what you want to do! So, take some time today to learn about Java garbage collection by reading our blog post below.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

1 thought on “Garbage Collection in Java”

Leave a Comment