What is Garbage Collection in Java?
Explore IBM's Garbage Collection in Java solution Subscribe to AI Topic Updates
Illustration with collage of pictograms of gear, robotic arm, mobile phone
What is Garbage Collection in Java?

Garbage Collection is a key feature of the Java programming language that automatically manages memory allocation and deallocation for objects that are created in an eden space.

Garbage Collection in Java allows developers to focus on writing code without worrying about memory management, making Java a popular choice for building complex and large-scale applications. However, understanding how Garbage Collection works is essential for Java developers to optimize their code's performance and avoid common memory-related errors. 

In this guide, the fundamentals of Garbage Collection in Java are explored, including its benefits, different types of collectors, and best practices to follow while coding. So, let's dive in and explore how Garbage Collection works!

The Total Economic Impact™ of IBM Robotic Process Automation

See a cost and benefit analysis of IBM Robotic Process Automation (RPA).

Related content

Read the guide on observability

What is OutofMemoryErrors?

OutofMemoryError is a type of error that occurs when a program or application attempts to allocate more memory than the available amount. This error occurs when the Java Virtual Machine (JVM) or another platform runs out of memory while trying to run an application.

An OutofMemoryError typically occurs when an application or program tries to create new objects, but the JVM is unable to allocate memory to accommodate them. This error can also occur when an application is using too much memory and is not releasing it properly.

When an OutofMemoryError occurs, the application will usually crash and terminate. This error is common in programs that deal with large amounts of metadata, such as an image or video processing applications, or programs that handle large databases.

To resolve this error, you may need to increase the amount of memory available to the application or optimize the application's memory usage. This can be done by modifying the JVM parameters or by using a memory profiler tool to identify memory leaks or inefficient memory usage.

How does garbage collection work in Java?

In Java, all objects are stored on the heap, which is a portion of memory that is reserved for dynamic allocation of objects. When an object is no longer being referenced by any part of the program, it becomes eligible for garbage collection.

The garbage collector in Java periodically scans the heap memory to find objects that aren’t being used. The process of garbage collection involves several steps, including marking, sweeping, and compacting.

  • Marking - The first step of garbage collection involves marking all objects that are still being referenced by the program. This is done by starting with a set of root objects, such as global variables, local variables, and method parameters, and then tracing all the objects that are reachable from those roots. Objects that cannot be reached from the roots are considered eligible for garbage collection.

  • Sweeping - After the marking phase, the garbage collector sweeps through the Java heap to identify and reclaim the memory that is used by the objects that are no longer being referenced. This involves deallocating the memory that is used by the unused objects, and adding it back to the free memory pool.

  • Compacting - In some garbage collection algorithms, the sweeping phase is followed by a compaction phase, where the memory that is used by the remaining objects is rearranged to minimize fragmentation. This involves moving objects closer together and creating larger contiguous blocks of free memory.

The Java virtual machine (JVM) automatically performs garbage collection, so the programmer does not have to manually manage memory. The garbage collector runs on a separate thread and typically operates in the background, so it doesn't affect the normal execution of the program.

Types of garbage collectors in Java

There are two main types of Garbage Collection algorithms in Java: Full Garbage Collection and Incremental Garbage Collection.

Full or Major Garbage Collection

Full garbage collection is a process in which a garbage collector (a part of a programming language's runtime system) searches through all of the memory that is used by a program and compiles any objects that are no longer being used by the program. These objects are then marked as garbage and are eligible for removal from memory.

Full garbage collection is typically performed by the runtime system of a programming language that uses automatic memory management, such as Java or Python. During the process, the garbage collector pauses the program's execution to perform the search for garbage objects, which can result in a temporary slowdown in the program's performance.

Full garbage collection is usually triggered when the amount of memory that is used by a program reaches a certain threshold or when the program requests a new block of memory, and there is not enough free memory available. The goal of full garbage collection is to reclaim memory that isn’t needed by the program, making it available for use by other parts of the program or by other programs running on the same machine.

Incremental or Minor Garbage Collection

Incremental garbage collection is a type of memory management technique that is used by programming languages and runtime environments to automatically reclaim memory that is no longer needed by a program. It does so by identifying objects in memory that aren’t being used, and freeing up the memory they occupy so that it can be reused by other parts of the program.

In incremental garbage collection, the garbage collector periodically scans the program's memory for unreachable objects in the young generation's heap memory. Instead of stopping the program's execution during this scanning process, the garbage collector divides the scanning process into small, manageable pieces called "increments". During each increment, the garbage collector scans a portion of the program's memory, identifying any objects that are not needed and marking them as available for reuse.

By using increments, the garbage collector can reclaim memory in small chunks, without interrupting the program's execution for an extended period. This helps to ensure that the program remains responsive and doesn't experience significant pauses or delays as a result of the garbage collection process.

However, incremental garbage collection can be less efficient than other types of garbage collection techniques, such as mark-and-sweep or generational garbage collection, because it requires more frequent scans of the program's memory. Additionally, the use of increments can introduce some overhead into the program's execution, as the garbage collector needs to maintain state information between each increment.

Java garbage collection benefits

Overall, Java's garbage collection provides many benefits that make it a valuable tool for developers. Here are some benefits of using Java's garbage collection:

  1. No manual memory management
  2. Prevents memory leaks
  3. Dynamic memory allocation
  4. Better performance
  5. Memory optimization
  • No manual memory management: With garbage collection, developers do not have to manually manage memory allocation and deallocation. This means that programmers can focus more on writing code and less on managing memory, which can help reduce errors and improve productivity.

  • Prevents memory leaks: Garbage collection helps prevent memory leaks, which can occur when a program does not release memory that is no longer needed. This can cause the program to consume more memory than necessary, leading to slow performance, and eventually crashing.

  • Dynamic memory allocation: Java's garbage collection enables dynamic memory allocation, which means that memory is allocated as needed at runtime. This helps prevent memory allocation errors and can make the program more efficient.

  • Better performance: Garbage collection can help improve the performance of a program by reducing the amount of time spent managing memory. This can lead to faster execution times and a more responsive program.

  • Memory optimization: Garbage collection can optimize the use of memory by reusing memory that is not used by one part of the program for other parts of the program. This can help reduce memory usage and improve overall program efficiency.

Developers benefit from Java garbage collection’s ability to automatically manage memory, prevent memory leaks, enable dynamic memory allocation, improve performance, and optimize memory usage, garbage collection can help developers write better, more efficient programs.

What events trigger Java garbage collection?

In Java, garbage collection is triggered automatically by the JVM (Java Virtual Machine) when it determines that the heap is getting full or when a certain amount of time has passed.

There are several events that can trigger garbage collection in Java:

  • Heap space allocation: When the JVM needs to allocate memory for a new object, and there is not enough space in the heap, it triggers garbage collection to reclaim unused memory or store them in the survivor space.

  • System.gc() method call: You can explicitly request garbage collection by calling the System.gc() method, although there is no guarantee that it will run.

  • Old generation threshold: Garbage collection can also be triggered when the heap size of the old generation heap space (which stores long-lived objects) reaches a certain threshold.

  • PermGen/Metaspace threshold: In Java versions before Java 8, garbage collection can also be triggered when the size of the PermGen (Permanent Generation) or Metaspace (in Java 8 and later) memory areas reaches a certain threshold.

  • Time-based: Sometimes, garbage collection can be triggered based on a time interval. For example, the JVM might trigger garbage collection every hour or every day, regardless of memory usage.

It's worth noting that the exact behavior of garbage collection in Java can vary depending on the JVM implementation and configuration.

How to request JVM to run Garbage Collector

To request the Java Virtual Machine (JVM) to run garbage collector, you can follow these steps:

  1. Call the System.gc() method: This method is used to request the JVM to run the garbage collector. It is not guaranteed that the garbage collector will run immediately after this method is called.

  2. Use the Runtime.getRuntime().gc() method: This method is similar to the System.gc() method, but it is less likely to be overridden by the JVM implementation.
  3. Use the -XX:+DisableExplicitGC JVM flag: This flag disables explicit garbage collection requests. This means that even if you call System.gc() or Runtime.getRuntime().gc(), the garbage collector will not be triggered.

It's important to note that explicitly requesting the garbage collector to run is generally not recommended, as the JVM is designed to automatically manage memory allocation and garbage collection. Explicit garbage collection requests can sometimes have a negative impact on performance. 

When is an Object eligible for Garbage Collection?

An object in a programming language is eligible for garbage collection when it is no longer referenced by any part of the program. Automatic garbage collection is a process that is performed by the programming language runtime environment to reclaim memory.

In most modern programming languages, garbage collection is performed automatically by the runtime environment. The specific algorithms that are used for garbage collection can vary depending on the programming language and implementation, but the general principle is the same: the runtime environment periodically scans the heap (the portion of memory that is used for dynamically allocated objects) to identify objects that are no longer reachable from any live object in the program. Once an object is identified as not being reachable, it is marked as garbage, and its memory can be reclaimed.

The exact timing of when an object is eligible for garbage collection depends on the specific garbage collection algorithm that is used by the runtime environment. Some algorithms are more aggressive than others and may reclaim memory more quickly, while others may delay garbage collection to optimize performance. However, in general, the programmer does not need to worry about managing memory manually, as the runtime environment takes care of this automatically.

What garbage collectors are available for Java?

There are several java garbage collectors, including:

  1. Serial Garbage Collector
  2. Parallel Garbage Collector
  3. Concurrent Mark Sweep (CMS) Collector
  4. G1 Garbage Collector
  • Serial Garbage Collector: The Serial Collector is the default garbage collector in Java and is typically used in small to medium-sized applications that do not require high throughput. This type of collector helps prevent the common “stop the world” events from occurring.

  • Parallel Garbage Collector: The Parallel Collector is designed for high-throughput applications and is particularly useful in applications that require large heaps because it uses multiple CPUs to speed up the process. It’s important to note that this type of collector freezes application threads when you run a garbage collector.

  • Concurrent Mark Sweep (CMS) Collector: The CMS Collector is designed for applications that require low pause times and is useful in applications that have many live objects.

  • G1 Garbage Collector: The G1 Collector is designed for large heaps and can handle a mix of short and long-lived objects. It uses multiple threads to concurrently scan and compact the heap.

Each garbage collector has its own strengths and weaknesses, and the choice of which collector to use depends on the specific needs of the application. It is also possible to configure and tune the garbage collector settings to optimize performance for a particular application.

What is the difference between garbage collection and memory leak?

Garbage collection and memory leaks are both related to memory management in computer programs, but they have different meanings and implications.

As stated previously, garbage collection is typically performed by the programming language or runtime environment, and it helps ensure that programs do not consume more memory than they need to. Garbage collection identifies memory that is free to use by other parts of the program or by other programs running on the computer.

On the other hand, a memory leak occurs when a program fails to release the memory that it has allocated, even when that memory is no longer needed. As a result, the program continues to consume memory over time, leading to the eventual depletion of available memory, which can cause the program or the entire operating system to crash. Memory leaks are typically caused by bugs in the program, and they can be difficult to identify and fix.

In summary, garbage collection is a process for automatically freeing up memory that is no longer needed. Memory leaks occur when memory is allocated but not released by a program, causing a gradual accumulation of memory usage.

Instana Can Help You Monitor Java Application Performance

In conclusion, Garbage Collection is an essential aspect of Java programming that ensures efficient memory management by reclaiming unused memory. Instana observability provides developers with powerful tools to monitor and optimize the garbage collection process in real time. 

By using Instana, developers can quickly identify memory leaks, optimize garbage collection settings, and troubleshoot performance issues that are related to garbage collection.

With Instana's comprehensive monitoring capabilities, developers can gain deep insights into their Java applications' memory usage and garbage collection behavior, enabling them to deliver high-performing and reliable software. 

By following the best practices outlined in this guide, developers can use Instana to optimize the garbage collection process and improve the overall performance of their Java applications. With Instana observability, developers can stay ahead of any issues that may arise, ensuring that their applications are performing at their best always.

Related products
IBM Instana Observability

Boost functionality and observability in your enterprise APM; improve application performance management and accelerate CI/CD pipelines no matter where applications reside.

Explore IBM Instana Observability

Resources What is observability?

Observability provides deep visibility into modern distributed applications for faster, automated problem identification and resolution

What is Java?

Learn why Java remains such a popular development platform and how it accelerates projects and supports a wide range of emerging technologies.

What is software development?

Learn the essentials of software development and how it helps businesses innovate and compete

What is the Java Runtime Environment (JRE)?

Learn what the Java Runtime Environment (JRE) does and how it works with other Java platform components to run Java applications.

What is application performance management (APM)?

Predict and prevent performance issues before they impact your business with application performance management

What is site reliability engineering (SRE)?

Automate IT operations tasks, accelerate software delivery, and minimize IT risk with site reliability engineering

Take the next step

IBM Instana provides real-time observability that everyone and anyone can use. It delivers quick time-to-value while verifying that your observability strategy can keep up with the dynamic complexity of current and future environments. From mobile to mainframe, Instana supports over 250 technologies and growing. 

Explore IBM Instana Book a live demo