Java Garbage Collection 101— Java 8 Changes, Interview questions, Commands & Algorithms

Everything and anything you should know about Garbage Collection

Varsha Das
Javarevisited
10 min readJan 16, 2024

--

I have never paid enough attention to the intricacies of Garbage Collection until one day when I could not find a root cause of the java ‘Outofmemory’ error in one of my workloads.

I didn’t even realize the importance of knowing the Xmx and Xms parameters for tuning heap memory. (can you imagine?)

And I am pretty sure this might resonate with anyone who actually never went beyond finalize() and System.gc() to understand Garbage Collection.

Then, I decided to explore more on this and figure out what are the essential things I must know about this topic.

Ensure you don’t miss the surprise waiting for you at the end of this article — read on for an extra dose of excitement and a surprise announcement.

It boils down to 3 things (as per my research):

  1. Basic understanding of memory.
  2. How does Garbage Collector work internally (several algorithms)
  3. Troubleshooting commands

Top 6 Most Popular System Design Articles:

1. How to Prepare for System Design Interview

2. Top 5 System Design CheatSheets (FREE)

3. Top 5 Websites to learn System Design in depth

4. Software Design Interview Questions for interviews

5. Must Read Books for System Design and Software Architecture

6. How does URL Shortner like TinyURL work?

The Basics:

Before we dive deep into the world of Garbage Collection in Java, let’s build a solid foundation.

Garbage collection = automatic memory management.

In simple words, removing unused objects from heap memory is known as Garbage collection.

Java’s memory is divided into two parts: Stack (stores variables and methods) and Heap (dynamic allocation of objects).

As developers, we do not need to manually allocate or deallocate memory for objects (unlike C/C++), improving our productivity and leveraging the overall performance. Garbage collector automatically identifies objects that are no longer reachable or referenced by the program and reclaims their memory.

An in-use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused or unreferenced object is no longer referenced by any part of your program

Interview Questions:

I started my research by first exploring the kind of interview questions being asked because that would cover many topics anyway.

Below are some of them, starting from scratch.

  1. Differentiate between Heap vs Stack Memory in Java.
  2. What are the different parts of the heap?
  3. Differentiate between PermGen vs Metaspace.
  4. What is garbage collection?
  5. Which part of the memory is involved in Garbage Collection? Stack or Heap?
  6. How do you identify minor and major garbage collection in Java?
  7. What is the algorithm for garbage collection in Java?
  8. What is finalize() method in Java? When does Garbage collector calls finalize method in Java?
  9. What are the different ways to make an object eligible for Garbage Collection when it is no longer needed?
  10. What are different ways to call garbage collector?

To know the answers to these questions, be sure to check out this YouTube video, where all the details are thoroughly covered (with code, diagrams, illustrations).

But that’s not all.

You would also want to know about the algorithms that run behind-the-scenes.

Algorithms for Garbage Collection:

  1. Serial Garbage Collector:
  • Single-threaded garbage collector — uses generational garbage collection.
  • The Serial Collector focuses on garbage collection in the Young Generation, where most short-lived objects are allocated.
  • When the Young Generation is filled, a minor garbage collection occurs, and live objects are copied to a new space, leaving the old space for new allocations.
  • Stop-the-world approach; pauses the application thread to carry out both minor and major garbage collection.

Stop-the-world: Meaning that all application threads are paused during garbage collection. This pause can lead to brief periods of unresponsiveness in the application.

  • It performs minor garbage collection when young generation is full, and major garbage collection in the old generation.
Source

Use Cases: Suitable for applications with low memory requirements or single processor machines. Often recommended for client-side applications or environments with small heaps, where low latency is a priority over throughput.

It may be suitable for applications with limited hardware resources or those running on environments with a single processor.

To activate Serial GC, we can use this command:

java -XX:+UseSerialGC -jar Appl.java

2. Parallel Garbage Collector:

  • Multi-threaded garbage collector — also uses generational garbage collection mechanism.
  • It uses multiple threads for garbage collection tasks, taking advantage of multi-core processors to perform collections more quickly.
  • Follows stop-the-world approach, pauses the application thread to carry out both minor and major garbage collection.

Source

Use cases: Suitable for applications with medium to large-sized heaps and multi-core systems.

To activate Parallel GC, we can use this command:

java -XX:+UseParallelGC -jar Appl.java

3. Concurrent Mark Sweep Garbage Collector (CMS GC):

The CMS Collector focuses on reducing pause times compared to collectors that operate in a stop-the-world manner.

  • The CMS Collector consists of multiple phases, including an initial marking phase, a concurrent marking phase, a remarking phase, and a sweeping phase. The concurrent marking phase, in particular, is designed to run concurrently with the application threads to identify reachable objects.
  • It aims to minimize the impact on application responsiveness by running certain phases of the garbage collection concurrently with the application threads.
  • CMS GC was deprecated from Java 9, and officially removed in Java 14.

Use cases: CMS is often used in applications where low-latency is a priority, such as interactive or web-based applications.

It is suitable for scenarios where short pause times are crucial, but some increase in overall CPU usage is acceptable.

To activate CMS, we can use this command:

java -XX:+UseConcMarkSweepGC -jar Appl.java

4. Garbage First GC(G1 GC):

  • G1 is designed to provide more predictable and consistent pause times compared to collectors like the Concurrent Mark Sweep (CMS) collector. It achieves this by using the concept of “pause time goals.”
  • G1 adapts its garbage collection strategy based on the application’s behavior and memory usage patterns. It dynamically adjusts parameters to meet the defined pause time goals.
  • As per Oracle docs:

G1 performs a concurrent global marking phase to determine the liveness of objects throughout the heap. After the mark phase completes, G1 knows which regions are mostly empty. It collects in these regions first, which usually yields a large amount of free space. This is why this method of garbage collection is called Garbage-First.

As the name suggests, G1 concentrates its collection and compaction activity on the areas of the heap that are likely to be full of reclaimable objects, that is, garbage.

Source

Read more: https://www.oracle.com/technetwork/tutorials/tutorials-1876574.html

Use Cases: G1 GC is suitable for a wide range of applications, including those with large heaps and stringent latency requirements.

It is often recommended for server-side applications where a balance between throughput and low-latency is essential.

To activate G1 GC, we can use this command:

java -XX:+UseG1GC -jar Application.java

4. Z Garbage Collector:

ZGC is a scalable low-latency garbage collector capable of handling heaps ranging from 8MB to 16TB in size, with sub-millisecond max pause times.

  • Introduced in Java 14 with several experimentations done before, it is a scalable low-latency garbage collector.

ZGC was initially introduced as an experimental feature in JDK 11, and was declared Production Ready in JDK 15. In JDK 21 was reimplemented to support generations.

  • Performs operations concurrently, without interrupting the execution of application threads.
  • Performs all expensive work concurrently, without stopping the execution of application threads for more than a millisecond.
  • It uses colored pointers to keep track of heap usage, enabling concurrent operations during thread execution.

Source

Use Cases: Applications that require low latency, or use very large heaps.

Read more : https://wiki.openjdk.org/display/zgc/Main

To activate Z GC, we can use this command:

java -XX:+UseZGC -jar Application.java
Oracle

If you’re liking what you’re reading, you’re going to love what I have in store for you on my YouTube channel.

Photo by krakenimages on Unsplash

We’re providing a range of exclusive perks, such as virtual video collaborations, member-only polls, premium content only for our members, and so much more.

In the context of this article, our exclusive videos will guide you through all the essential aspects of system design, common interview questions about Java threads and concurrency, more topics on java memory mangement, detailed plans for Spring Boot projects, and plenty of project ideas. All this special content is just for you!

Time for the announcement:

If you’re liking what you’re reading, you’re going to love what I have in store for you on my YouTube channel.

We’re providing a range of exclusive perks, such as virtual video collaborations, member-only polls, premium content only for our members, and so much more.

In the context of this article, our exclusive videos will guide you through all the essential aspects of system design, deep-dive into the components, offer extra insights into math concepts, share valuable tips, and provide actionable strategies that can strengthen your System design skills.

Who am I?

Across 7 years, I have led projects on AWS, Java, Spring Boot, Kafka, ELK stack, Splunk, Apache Mesos, etc, optimizing systems for cost-effectiveness, achieving savings of up to 30% , reduced latency by 50% through performance tuning techniques, and enabled systems to handle a higher volume of transactions.

So, I am quite certain you can rely on my expertise.

In addition to that, we will also have videos dedicated to common interview questions about Java threads and concurrency, detailed plans for Spring Boot projects, and plenty of project ideas. All this special content is just for you!

As you support our channel, join our expanding community and get access to things you won’t find anywhere else.

To become a valued member right now, click this link.

Garbage Collection commands:

You might need to know this if there’s a production incident or you want to optimise the program performance.

  • jstat: Prints statistics and information about garbage collection, heap utilization, and more.
jstat -gc <pid>
  • jmap: Prints heap configuration and usage statistics for a given process ID( <pid>).
jmap -heap <pid>
  • jcmd: Prints a histogram of the heap by class.
jcmd <pid> GC.class_histogram
  • jvisualvm: Visual monitoring, troubleshooting, and profiling tool
jvisualvm
  • Enable GC Logging to a File:
  1. -Xloggc:/path/to/gc.log: Specifies the file path for GC logging.
  2. -XX:+UseGCLogFileRotation: Enables log rotation.
java -Xloggc:/path/to/gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -jar your-application.jar
  • To measure maximum pause time during garbage collection:
jcmd <pid> GC.maxGCPauseMillis

Setting heap size:

-Xms512m  # Set initial heap size to 512 megabytes
-Xmx2g # Set maximum heap size to 2 gigabytes

Print Heap Information After GC:

-XX:+PrintHeapAtGC

Printing GC Details along with timestamps:

-XX:+PrintGCDetails -XX:+PrintGCDateStamps

Java 8 Garbage Collection improvements:

Metaspace:

Java 8 replaced the Permanent Generation (PermGen) with Metaspace, a memory area for class metadata.

Metaspace is more flexible and dynamically adjusts its size, reducing the likelihood of PermGen-related errors. It simplifies GC tuning and mitigates issues associated with the fixed size of PermGen.

G1 Garbage Collector Enhancements:

In Java 8, the Garbage-First (G1) Garbage Collector became the default collector for the HotSpot JVM.

While G1 was introduced in Java 7, Java 8 continued to refine its capabilities. G1 aims for better predictability, lower-latency pauses, and improved overall performance, especially for applications with large heaps.

Parallel Full GC for G1:

Java 8 introduced a parallel approach to full garbage collection in G1. This parallelization enhances throughput and reduces the impact of full garbage collection pauses.

String Deduplication:

String deduplication was introduced as a G1-specific feature in Java 8.

The G1 collector identifies and removes duplicate instances of strings in the heap, contributing to reduced memory consumption.

Thanks for reading.

If you liked this article, please click the “clap” button 👏 a few times.

It gives me enough motivation to put out more content like this. Please share it with a friend who you think this article might help.

Subscribe here to receive alerts whenever I publish an article.

If you enjoyed reading this, you could buy me a coffee here.

Connect with me — Varsha Das | LinkedIn

Follow my Youtube channel — Code With Ease — By Varsha, where we discuss Java & Data Structures & Algorithms and so much more.

If you guys got some value from this Medium article and also love my YouTube videos, please don’t forget to nominate me for the National Creator Awards, India, under the following category:

Nominate here — https://innovateindia.mygov.in/national-creators-award-2024/login/

Stats:

Linkedin profile (Primary) :https://www.linkedin.com/in/varsha-das-se

Followers : 2741

Youtube url (Secondary) : https://youtube.com/@codewithease-byvarsha

Followers : 1770

Last date — 29th February, 2024

Other articles you would want to check out:

  1. Java Streams — A Practical Guide
  2. The Layman’s Guide to Kubernetes: Understanding Containerization and More
  3. Top 19 OOPS Questions That You Need to Know
  4. Steal these 9 HACKS to improve logic-building skills in programming

Happy learning! 😁

--

--

Varsha Das
Javarevisited

"Senior Software Engineer @Fintech | Digital Creator @Youtube | Thrive on daily excellence | ❤️ complexity -> clarity | Devoted to health and continuous growth