Garbage Collection in Java

Mayank Jain
Javarevisited
Published in
2 min readFeb 3, 2024

Garbage collection is the process of removing the unused objects from the heap memory and hence freeing up space. This prevents us from running into out of memory errors and ensures efficient memory management.

Types of JVM garbage collectors —

a) Serial GC — This garbage collector is the most basic one and it uses only a single thread. The problem with this GC is, whenever we call this, it blocks all the running threads of the application and performs the cleaning of memory. This GC is best suited when we have our application running in a single core machine.

-XX:+UseSerialGC

b) Parallel GC — Parallel GC is the default GC in java 8. This is similar to serial GC as it also freezes the application threads when GC is called.

-XX:+UseParallelGC

The main advantage of this GC is that it can leverage the multiple cores of the machine since it uses multiple threads to clean up the memory that is no longer in use. This GC also provides us few more attributes thus giving more control over it.

XX:+UseParallelGC -XX:ParallelGCThreads=n -XX:MaxGCPauseMillis=m 

c) G1GC — G1GC stands for Garbage first garbage collector, this is basically used for applications that require more memory space i.e at least 4GB and run on machines with multicore processors. This is the default GC in java9. It was first introduced in java 7. It divides the heap into equal size regions ranging from 1MB to 32MB. This GC uses the Mark and Sweep algorithm, in the mark phase, G1 determines the live and dead objects throughout the heap in concurrent manner. After this phase is completed, GC has complete information of regions that contains the most garbage so those regions are sweep first.

-XX:+UseG1GC -XX:MaxGCPauseMillis=200 
-XX:ParallelGCThreads=n (sets number of "stop the world worker threads". Sets
the value of n to the number of logical processors)
-XX:ConcGCThreads=n (sets number of parallel marking threads)
-XX:InitiatingHeapOccupancyPercent=45 (sets heap occupancy threshold that
triggers marking phase)

Note — Java 8 introduces a new feature to prevent String Deduplication, this removes memory consumption by identifying and eliminating duplicate String objects from String Constant Pool.

-XX:+UseStringDeduplication

Few fine tuning attributes are —

-XX:MinHeapFreeRatio=20 (sets the minimum percentage of heap that should be 
remain free after a garbage collection to avoid further garbage collection)

-XX:MaxHeapFreeRatio=40 (sets the maximum percentage of the heap that can be
free after a garbage collection)

References —

  1. https://www.baeldung.com/jvm-garbage-collectors

--

--