Java Garbage Collection

Zaid Shaikh
8 min readApr 23, 2021

Introduction

In C/C++, programmer is responsible for both creation and destruction of objects. You can use methods like free() in C, and delete() in C++ to perform Garbage Collection. Usually programmer neglects destruction of useless objects. Due to this negligence, at certain point, for creation of new objects, sufficient memory may not be available and entire program will terminate abnormally causing OutOfMemoryErrors.

But in Java, the programmer need not to care for all those objects which are no longer in use. Garbage collector destroys these objects.

Main objective of Garbage Collector is to free heap memory by destroying unreachable objects.

Definition

Java garbage collection is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.

How Java Garbage Collection Works

Java garbage collection is an automatic process. The programmer does not need to explicitly mark objects to be deleted. The garbage collection implementation lives in the JVM. Each JVM can implement garbage collection however it pleases; the only requirement is that it meets the JVM specification. Although there are many JVMs,. It offers a robust and mature set of garbage collection options.

In the first step, unreferenced objects are identified and marked as ready for garbage collection. In the second step, marked objects are deleted. Optionally, memory can be compacted after the garbage collector deletes objects, so remaining objects are in a contiguous block at the start of the heap. The compaction process makes it easier to allocate memory to new objects sequentially after the block of memory allocated to existing objects.

The heap is divided into three sections:

Young Generation: Newly created objects start in the Young Generation. The Young Generation is further subdivided into an Eden space, where all new objects start, and two Survivor spaces, where objects are moved from Eden after surviving one garbage collection cycle. When objects are garbage collected from the Young Generation, it is a minor garbage collection event.

Old Generation: Objects that are long-lived are eventually moved from the Young Generation to the Old Generation. When objects are garbage collected from the Old Generation, it is a major garbage collection event.

Permanent Generation: Metadata such as classes and methods are stored in the Permanent Generation. Classes that are no longer in use may be garbage collected from the Permanent Generation.

During a full garbage collection event, unused objects in all generations are garbage collected.

How can an object be unreferenced?

There are many ways:

1) By nulling the reference

2) By assigning a reference to another

3) By anonymous object etc.

1) By nulling the reference

2) By assigning a reference to another:

3) By anonymous object:

Methods to Perform Cleanup :

Finalize() method

The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:

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

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

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

Unreachable Objects in Java

When an object does not contain any “reachable” reference to it, then we call it an unreachable object. These objects can also be known as unreferenced objects.

Example of unreachable objects :

Eligibility for Garbage Collection in Java

An object can be eligible for garbage collection in Java if and only if it is unreachable. In the above program, after declaring d as null; double object d in the heap area becomes eligible for garbage collection.

Ways of requesting JVM to run Garbage Collector :

Even if we make an object eligible for Garbage Collection in Java, it may or may not be eligible for Java Virtual Machine (JVM) to destroy. So there are some ways to request JVM to destroy this object and perform garbage collection.

There are two ways to request JVM for Garbage collection in Java which are:

· Using System.gc() method

· Using Runtime.getRuntime().gc() method

A Real-life Example of Garbage Collection

Let’s take a real-life example of a garbage collector.

Suppose you go for an internship at a particular company and you have to write a program that counts the number of employees working in the company, excluding interns. To implement this task, you have to use the concept of a garbage collector.

The actual task given by the company:

Question. Write a program to create a class Employee having the following data members.

1. An ID for storing unique id for every employee.

And, the class will have the following methods:

1. A default constructor to initialize the id of the employee.

2. A method show() to display ID.

3. A method showNextId() for displaying the ID of the next employee.

we have to request a garbage collector, and to do this, we have to write the following three steps before closing the brace of sub-block.

1. Set references to null (that is, X = Y = null;)

2. Call System.gc();

3. Call System.runFinalization();

Output :

Types of Garbage Collectors

JVM has four types of Garbage Collector implementations which are

1. Serial Garbage Collector

2. Parallel Garbage Collector

3. CMS Garbage Collector

4. G1 Garbage Collector

Now, we will briefly discuss each type of garbage collector.

1. Serial Garbage Collector

It is the simplest Garbage Collector implementation as it basically works with a single thread and all the garbage collection events are conducted serially in one thread. As this collector can work on a single thread, it freezes all application threads when it runs. Hence, it is not preferred to use it in multi-threaded applications like server environments.

We can use the following argument to enable Serial Garbage Collector:

2. Parallel Garbage Collector

It is the default Garbage Collector of the JVM and sometimes called Throughput Collectors. Unlike the Serial Garbage Collector, the Parallel Garbage Collector uses multiple threads to manage heap space. But at the same time, it also suspends other application threads while performing garbage Collection. Using this Garbage Collector, we can specify the maximum garbage collection threads throughput and footprint (heap size) and, pause time.

We can use the following argument to enable Parallel Garbage Collector,

3. CMS (Concurrent Mark Sweep) Garbage Collector

The CMS Garbage Collection implementation uses multiple threads for garbage collection. This Garbage Collector is designed for applications that can afford to share processor resources with the garbage collector while the application is running and that prefer shorter garbage collection pauses. Simply we can say that applications using CMS respond slower on average but do not stop responding to perform garbage collection.

We can use the following flag to enable the CMS Garbage Collector:

4. G1(Garbage First) Garbage Collector

G1 (Garbage First) Garbage Collector is the newest garbage collector which is designed as a replacement for CMS. It performs more efficiently as compared to CMS Garbage Collector. It is similar to CMS and is designed for applications running on multiprocessor machines with large memory space.

To enable the G1 Garbage Collector, we can use the following argument:

Advantages of Garbage Collection:

There is no need to manually handle the memory allocation/deallocation because the JVM automatically performs the Garbage Collection for unused space in Java.

There is no overhead of handling the Dangling Pointer.

Garbage Collection takes care of a good portion of Automatic Memory Leak management.

Disadvantages of Garbage Collection:

There is a more requirement of CPU power besides the original application, as JVM has to keep track of object reference creation/deletion. This may affect the performance of requests which require a huge memory.

Programmers do not have any control over the scheduling of CPU time dedicated to freeing the unreachable objects.

Using some Garbage Collection implementations an application may stop unpredictably.

Automatic memory management is not much efficient proper manual memory allocation/deallocation.

Summary

Garbage Collection in Java is useful for preventing memory leaks and for utilizing the space. In this Java tutorial, we learned about the garbage collection in Java and its working. We discussed the important terms related to Java Garbage Collection. We also covered the algorithm for garbage collection. There are four types of Java Garbage Collectors which we learned in this article. We discussed the Java Mark and Sweep algorithm along with its pros and cons. We also had a look at the advantages and disadvantages of the Garbage Collection in Java.

References

  1. https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html
  2. https://techvidvan.com/tutorials/java-garbage-collection/
  3. https://www.javatpoint.com/Garbage-Collection
  4. https://www.geeksforgeeks.org/garbage-collection-java/
  5. Core Java Volume I — Fundamentals

--

--

Zaid Shaikh

Undergraduate from Vishwakarma Institute of Technology Pune, Department of Computer Science and Engineering. Tech Enthusiast. Coder❤