Garbage collection

Garbage Collection (GC) is one of the most important features of the Java Virtual Machine (JVM).

Java developers don't explicitly allocate and release memory like developers working with languages such as C or C++. The JVM manages object memory automatically through Garbage Collection.

However, automatic memory management doesn't mean developers can ignore memory management.

In real-world enterprise applications, especially high-throughput Spring Boot microservices, inefficient object allocation, memory leaks, excessive garbage collection, and poor JVM configuration can directly impact application performance and availability.

Understanding how modern Java Garbage Collection works is essential for building scalable and reliable backend systems.

Let's explore it from fundamentals to production-level considerations.

1. Understanding Java Heap Memory

The JVM divides memory into different runtime areas. The Heap is where most Java objects are allocated.

Consider the following example:

public class CustomerService { public void processCustomer() { Customer customer = new Customer(); customer.setId(101); customer.setName("John"); } } 

When new Customer() executes:

  • Memory is allocated for the Customer object in the heap.
  • The local variable customer holds a reference to the object.
  • Once the method completes, the local reference goes out of scope.
  • If no other reachable reference exists, the object becomes eligible for Garbage Collection.

Important: An object becoming eligible for GC does not mean it will be collected immediately.

2. How Heap Memory Is Organized

Traditionally, the JVM uses a generational memory model.

The heap is conceptually divided into:

Young Generation

  • Eden Space
  • Survivor Space S0
  • Survivor Space S1

Old Generation

  • Stores objects that survive multiple garbage collection cycles or are allocated directly into the old generation, depending on the collector and allocation behavior.

How object allocation works

  1. New objects are typically allocated in Eden.
  2. When Eden becomes full, a Minor GC occurs.
  3. Live objects are copied or otherwise preserved in survivor spaces.
  4. Objects that survive multiple collection cycles may be promoted to the Old Generation.
  5. Old Generation memory is reclaimed during appropriate collection cycles.

This generational approach is based on an important observation:

Most objects in Java applications have short lifetimes.

For example, temporary DTOs, request objects, intermediate collections, and serialization objects are frequently short-lived in Spring Boot applications.

3. How Garbage Collection Works

Garbage Collection identifies objects that are no longer reachable and reclaims their memory.

The JVM uses GC Roots to determine object reachability.

Common GC Roots include:

  • Local variables and references in active thread stacks.
  • Static references.
  • Active Java threads.
  • JNI references.
  • Certain JVM internal references.

Consider:

public class OrderService { public void processOrder() { Order order = new Order(); order.setOrderId(1001); order = null; } } 

After order = null, the previously referenced object may become eligible for Garbage Collection, assuming no other references exist.

The JVM uses reachability analysis rather than simply counting references.

This distinction is important because circular references do not prevent objects from being collected if they are unreachable from GC Roots.

4. Understanding Major Garbage Collectors in Modern Java

Java has evolved significantly in its Garbage Collection implementations.

Different collectors target different application requirements.

A. Serial GC

  • Uses a single thread for garbage collection.
  • Performs collection with application threads paused.
  • Suitable for small applications with limited memory.
  • Not generally preferred for high-throughput enterprise applications.

B. Parallel GC

  • Uses multiple threads for garbage collection.
  • Focuses on maximizing application throughput.
  • Can introduce longer Stop-The-World pauses.
  • Useful for workloads where throughput is more important than low latency.

C. G1 Garbage Collector

G1 (Garbage-First) is a widely used collector and the default collector in modern server-class JVM configurations.

Key characteristics:

  • Divides the heap into multiple regions.
  • Prioritizes regions with more reclaimable memory.
  • Performs concurrent marking.
  • Supports configurable pause-time goals.
  • Balances throughput and pause-time requirements.

Enable G1 explicitly:

java -XX:+UseG1GC -jar application.jar 

Configure a pause-time goal:

-XX:MaxGCPauseMillis=200 

Note: This is a target, not a guaranteed maximum pause duration.

D. ZGC

ZGC is designed for low-latency applications and supports very large heaps.

Key characteristics:

  • Performs most GC work concurrently.
  • Aims for very short pause times.
  • Suitable for latency-sensitive workloads.
  • Available in modern Java releases.

Enable ZGC:

java -XX:+UseZGC -jar application.jar 

E. Shenandoah GC

Shenandoah is another low-pause garbage collector.

Key characteristics:

  • Performs much of its work concurrently with application execution.
  • Focuses on reducing pause times.
  • Useful for latency-sensitive workloads.

Availability depends on the JDK distribution.

5. Understanding Stop-The-World (STW) Events

Stop-The-World means application threads are temporarily paused while the JVM performs certain GC operations.

For example, imagine a Spring Boot application processing 5,000 requests per second.

If a GC pause temporarily stops application threads:

  • Requests may experience increased latency.
  • Response times may become unpredictable.
  • Request queues may grow.
  • Downstream services may experience timeouts.
  • Overall throughput may decrease.

Not every GC phase is Stop-The-World. Modern collectors such as G1, ZGC, and Shenandoah perform significant work concurrently.

The objective is to balance memory reclamation, application throughput, and pause-time requirements.

6. Memory Leaks in Java: Why They Still Happen

One common misconception is that Java cannot have memory leaks because it has Garbage Collection.

Java applications can absolutely experience memory leaks.

A memory leak occurs when objects are no longer needed but remain reachable through references.

Common causes include:

  • Static collections retaining unnecessary objects.
  • Improper cache management.
  • Unclosed resources.
  • Event listeners that are never removed.
  • ThreadLocal variables retaining references.
  • Unbounded queues.
  • Incorrectly managed application sessions.

Example:

public class CustomerCache { private static final List<Customer> CUSTOMERS = new ArrayList<>(); public void addCustomer(Customer customer) { CUSTOMERS.add(customer); } } 

If customers are continuously added without removing unnecessary entries, the collection keeps references to those objects.

The GC cannot reclaim them while they remain reachable.

In production applications, this can eventually lead to:

java.lang.OutOfMemoryError: Java heap space 

7. Monitoring Garbage Collection in Production

Monitoring GC is critical for enterprise Java applications.

Some useful JVM options and tools include:

Enable GC logging

-Xlog:gc*:file=gc.log:time,uptime,level,tags 

This generates detailed GC logs that help identify:

  • GC frequency.
  • Pause duration.
  • Heap utilization.
  • Memory allocation patterns.
  • Collection behavior.

Useful JVM diagnostic tools

Tool Purpose
jstat Monitor GC statistics
jcmd JVM diagnostic commands
jmap Heap information and dumps
Java Flight Recorder Analyze runtime behavior
Java Mission Control Analyze JVM performance
VisualVM Monitor heap and threads

For example:

jcmd <pid> GC.heap_info 

Generate a heap dump:

jcmd <pid> GC.heap_dump heapdump.hprof 

Heap dumps can be analyzed using tools such as Eclipse MAT to identify memory retention and potential leaks.

8. Garbage Collection in Spring Boot Microservices

Consider a banking application with multiple Spring Boot microservices:

  • Customer Service
  • Account Service
  • Payment Service
  • Transaction Service

Each service has its own JVM and memory allocation.

During high transaction volumes, services may create thousands of temporary objects.

Examples include:

  • Request and response DTOs.
  • JSON serialization objects.
  • Database result mappings.
  • Kafka consumer records.
  • Temporary collections.
  • Business validation objects.

If object allocation increases significantly, GC activity may also increase.

This can affect application latency and resource utilization.

Production optimization considerations

  1. Monitor heap utilization and allocation rates.
  2. Identify memory leaks using heap dumps.
  3. Analyze GC logs and pause times.
  4. Select a collector based on workload requirements.
  5. Configure container memory limits appropriately.
  6. Avoid unnecessary object creation in frequently executed code paths.
  7. Monitor CPU utilization alongside GC activity.

For Kubernetes or OpenShift deployments, JVM memory configuration must also account for container memory limits.

For example:

-Xms512m -Xmx2g -XX:+UseG1GC 

These are illustrative values, not universal production settings.

Remember that JVM process memory includes more than Java heap memory. Metaspace, thread stacks, direct buffers, code cache, and other native allocations also consume memory.

9. Practical Interview Questions

Here are some important Garbage Collection questions for experienced Java developers.

Q1. What is the difference between Minor GC and Major GC?

Minor GC traditionally refers to collection of the Young Generation. Major GC is commonly used to describe Old Generation collection, although terminology varies across collectors and JVM implementations.

Q2. Can we force Garbage Collection in Java?

We can request it using:

System.gc(); 

However, the JVM is not guaranteed to execute Garbage Collection immediately.

Q3. Can Java applications have memory leaks?

Yes. Objects that are no longer logically required can remain reachable through references, preventing GC from reclaiming them.

Q4. What is the difference between G1 GC and ZGC?

G1 balances throughput and predictable pause-time goals using region-based collection. ZGC focuses on very low pause times using concurrent garbage collection techniques.

Q5. What happens when Old Generation memory becomes full?

The collector attempts to reclaim memory. If sufficient memory cannot be recovered and the heap cannot expand, the application may eventually encounter an OutOfMemoryError.

Q6. What is the relationship between GC and application latency?

GC pauses can temporarily stop application threads, increasing response times. Allocation pressure and CPU consumed by GC can also affect latency.

10. Final Thoughts

Garbage Collection is not just a JVM background activity. It directly influences application performance, scalability, and reliability.

For experienced Java developers, understanding GC means going beyond knowing Minor GC, Major GC, and heap memory.

It means being able to:

  • Understand object allocation and reachability.
  • Identify memory leaks.
  • Analyze GC logs.
  • Interpret heap dumps.
  • Choose appropriate garbage collectors.
  • Optimize JVM configurations for production workloads.
  • Diagnose memory-related performance issues in distributed applications.

As Java continues to evolve, understanding modern Garbage Collection mechanisms becomes increasingly important for building high-performance enterprise applications.

The real goal is not to eliminate Garbage Collection. It is to design applications that work efficiently with the JVM's memory management.

Author: Ramu Boya

Java #Java21 #GarbageCollection #JVM #SpringBoot #Microservices #PerformanceEngineering #BackendDevelopment #SoftwareArchitecture