Different Ways to Collect Garbage in Java HotSpot JVM

Last Updated : 08 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JDKs come with different JVM implementations (Oracle HotSpot, Eclipse OpenJ9, GraalVM, Jikes RVM, Codename One), and different garbage collector implementations with different tuning options (Serial, Parallel, CMS, G1, Z, Shenandoah). In this article, we will know more about the Garbage Collector, how it works, and the various types of GC available in Java. We will also cover some of the new experimental Garbage Collectors that are available in the latest Java releases.

What is Garbage Collection in Java?

In C/C++, a programmer is responsible for both the creation and destruction of objects. Usually, programmer neglects the destruction of useless objects. Due to this negligence, at a certain point, sufficient memory may not be available to create new objects, and the entire program will terminate abnormally, causing OutOfMemoryErrors. We can use methods like free() in C, and delete() in C++ to perform Garbage Collection. In Java, garbage collection happens automatically during the lifetime of a program. This eliminates the need to de-allocate memory and therefore avoids memory leaks. Garbage Collection is the process by which we can reclaim the runtime unused memory by destroying the unused objects.

The objects created in the Java program are present in the heap memory of Java. Most of you would already be familiar with that. An object is eligible for garbage collection if there are no references to it in the heap memory. There are various ways in which the references to an object can be released to make it a candidate for Garbage Collection. Some of them are:

1. By Making Reference to object Null

Java




Student studentOne = new Student();
studentOne = null;
// new Student() object inline 1 function
// has lost its reference in line 2


2. By Using an anonymous object

Java




function(new Student());
// Student object in function 
// has no reference at all


3. By Pointing one’s reference to another object or reference

Java




Student studentOne = new Student();
Student studentTwo = new Student();
studentOne = studentTwo;
// "new Student()" object created 
// in line 2 is dereferenced in line 3


4. An Object created inside a method loses reference outside the method 

Java




public void function(){
  Student studentOne = new Student();
}
  
public static void Main(){
  function();
}
  
// Here after function() is called the object refered
// by studentOne will lose its reference.


Heap Memory Division

The heap memory area in the JVM is divided into three sections:

  1. Young Generation:  All New Objects are first stored here.
  2. Old Generation: Large objects are allocated memory here. Also, the objects in the young generation who survived minor garbage collection processes of the young generation are promoted here.
  3. Permanent Generation: Here the objects or metadata which are required by JVM for describing classes and methods are stored. This memory also stores classes as well as methods.
Heap Memory

Heap Memory

Types of Garbage Collectors in HotSpot Java

There are mainly 4 algorithms for garbage collectors in HotSpot Java:

1. Serial Garbage Collection

It is used where just one thread executed the GC (garbage collection). This collector freezes all application threads whenever it’s working. If we want to use the serial garbage collector, execute the -XX:+UseSerialGC JVM argument to activate it.

Serial GC

Serial GC

2. Parallel Garbage Collection

Where multiple minor threads are executed simultaneously. This collector also freezes all application threads whenever it’s working. If you want to use the parallel garbage collector, execute the -XX:+UseParallelGC JVM argument to activate it.

Parallel GC

Parallel GC

3. Concurrent Mark Sweep(CMS) Garbage Collection

It is similar to parallel, also allows the execution of some application threads, and reduces the frequency of stop-the-world GC. It has 2 phases: Mark Phase and Sweep Phase. The Mark phase  algorithm marks all the live objects in heap memory (those that have a reference) as “live” and others as “dead” while putting the applications on pause. The Sweep phase algorithm empties the space occupied by objects marked “dead”. In the Mark phase,  multiple minor threads are executed simultaneously to mark the live objects. In the Sweep phase,   multiple minor threads are executed simultaneously to sweep or delete the dead objects parallel to application threads. For this reason, it uses more CPU in comparison to other GC. It is also known as the concurrent low pause collector. If you want to use a CMS garbage collector, execute the -XX:+USeParNewGC JVM argument to activate it. We can also set the number of GC threads by using the -XX:ParallelCMSThreads=<n> JVM argument.

CMS Garbage Collection

CMS Garbage Collection

Note: The Concurrent Mark Sweep (CMS) collector is deprecated as of JDK 9, with the recommendation to use the G1 collector instead.

4. Generation First(G1) Garbage Collection

This GC is used if we have huge memory(>4GB). It partitions the heap into a set of equal size regions (1MB to 32MB - depending on the size of the heap) and uses multiple threads to scan them and mark the objects as live or dead. After marking, G1 knows which regions contain the most garbage objects. In the next step, it sweeps the objects in the region containing most garbage objects. G1 works concurrently with the application. This divides young and old generations of the heap into the following regions:

  • Eden region in memory where the objects are typically allocated when they are created.
  • Survivor Region contains the objects that have survived from the Young garbage collection or Minor garbage collection.
  • Tenured Region is where long-lived objects are stored. Objects are eventually moved to this space if they survive a certain number of garbage collection cycles. This space is much larger than the Eden space and the garbage collector checks it less often.
  • Humongous: It is used if the object size is large.
  • Available: It represents the unoccupied space.

An optimization is present in Java 8 (G1 Collector String deduplication). Since strings (and their internal char[] arrays) takes much of our heap, a new optimization has been made that enables the G1 collector to identify strings that are duplicated more than once across heap memory and correct them to point to the same internal char[] array, to avoid multiple copies of the same string from residing inefficiently within the heap. If you want to use G1 GC use  -XX:+UseStringDeduplicationJVM argument.

G1 GC Space Description

G1 GC Space Description

5. Z Garbage Collector

It’s the latest GC that can be used with Java 11 by explicitly setting it, and in Java 15 and beyond this is set as default. It’s a highly scalable, low-latency GC. It performs very expensive tasks concurrently without stopping the working of threads for more than 10ms. It can work on large heap memory (up to TBs). If you want to use ZGC, use XX:+UnlockExperimentalVMOptions -XX:+UseZGC.

ZGC Heap Regions

ZGC Heap Regions

Methods for Running Garbage Collector in Java

In Java, GC runs by itself. But there are some methods we can use in Java:

  • System.gc()
  • Runtime.getRuntime().gc() 

Best Practices to Use Garbage Collection

Collector choice is a primary concern as the wrong collector can hinder performance and render the application useless. For backend purposes, the CMS collector can prove to be useful in spite of having the disadvantage of stopping the application itself during garbage collection. However, the frontend of the application must not implement CMS because the UI must always be responsive. This calls for G1 collectors which can run concurrently with the application in itself. ZGC is the newest and provides very low latency and high throughput which can be used by applications that require low latency and uses large-size Heap. Whenever you are using garbage collections in Java it is important to note that you can never predict when the garbage collector will run. You can try to explicitly call the garbage collector by System.gc() and Runtime.gc(). However, even after explicitly calling the Garbage collector there is no guarantee that it will actually work.



Similar Reads

Types of JVM Garbage Collectors in Java with implementation details
prerequisites: Garbage Collection, Mark and Sweep algorithm Garbage Collection: Garbage collection aka GC is one of the most important features of Java. Garbage collection is the mechanism used in Java to de-allocate unused memory, which is nothing but clear the space consumed by unused objects. To deallocate unused memory, Garbage collector track
5 min read
How JVM Works - JVM Architecture
JVM(Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls the main method present in a Java code. JVM is a part of JRE(Java Runtime Environment). Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one system and expect it to run on any other Java-enabl
7 min read
Verification in Java (JVM)
After the class loader in the JVM loads the byte code of .class file to the machine the Bytecode is first checked for validity by the verifier and this process is called as verification. The verifier performs as much checking as possible at the Linking so that expensive operation performed by the interpreter at the run time can be eliminated. It en
3 min read
Java Virtual Machine (JVM) Stack Area
For every thread, JVM creates a separate stack at the time of thread creation. The memory for a Java Virtual Machine stack does not need to be contiguous. The Java virtual machine only performs two operations directly on Java stacks: it pushes and pops frames. And stack for a particular thread may be termed as Run – Time Stack. Every method call pe
4 min read
Difference between JIT and JVM in Java
Java Virtual Machine (JVM) is used in the java runtime environment(JRE). The original JVM was conceived as a bytecode interpreter. This may come as a bit of a surprise because of performance problems. Many modern languages are meant to be compiled into CPU-specific, executable code. The fact that the JVM executes a Java program, however, helps addr
4 min read
Difference Between 32-bit and 64-bit JVM in Java
One does not need to know the difference unless developing a performance-critical application. The minor distinction between 32-bit and 64-bit JVMs would make little difference in your application. Now coming onto the differences where we will be listing out some key differences between 32-bit and 64-bit Java Virtual Machines are listed below in wh
4 min read
JVM Shutdown Hook in Java
Shutdown Hooks are a special construct that allows developers to plug in a piece of code to be executed when the JVM is shutting down. This comes in handy in cases where we need to do special clean up operations in case the VM is shutting down.Handling this using the general constructs such as making sure that we call a special procedure before the
6 min read
Introduction to Java Mission Control for JVM Monitoring
Java Mission Control (JMC) is a powerful monitoring, diagnostics, and performance analysis tool. Oracle provides this to run the Java applications on the Java Virtual Machine. It is part of the Java Development Kit and offers developers and administrators insights into the runtime behaviour of Java applications. The JMC is useful for identifying pe
5 min read
How to prevent objects of a class from Garbage Collection in Java
The garbage collector in Java is automatic, i.e the user doesn't have to manually free an occupied memory which was dynamically allocated. And how does a garbage collector decide which object is to be deleted? It's simple: the object which loses it's reference, is marked for deletion from the heap memory. For example, look at the following piece of
5 min read
Z Garbage Collector in Java
Today, it's common for applications to respond to thousands or even millions of users concurrently. Such applications need immeasurable amounts of memory. However, managing all that memory may easily impact application performance. To overcome this issue java 11 includes a lot of improvements and changes in the GC(Garbage Collection) domain. Java 1
6 min read
Garbage Collection in Java
Garbage collection in Java 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
9 min read
Output of Java programs | Set 10 (Garbage Collection)
Prerequisite - Garbage Collection in Java Difficulty level : Intermediate In Java, object destruction is taken care by the Garbage Collector module and the objects which do not have any references to them are eligible for garbage collection. Below are some important output questions on Garbage collection. Predict the output of following Java Progra
4 min read
How to make object eligible for garbage collection in Java?
An object is eligible to be garbage collected if its reference variable is lost from the program during execution.Sometimes they are also called unreachable objects. What is reference of an object? The new operator dynamically allocates memory for an object and returns a reference to it. This reference is the address in memory of the object allocat
5 min read
How to Generate JVM Heap Memory Dump?
Java Heap dump is a snapshot of all java objects that are present in the JVM(Java Virtual Machine) at a certain point in time. The JVM allocates memory for objects which are class instances or arrays in the heap memory. When the objects are no longer needed or are no more referenced, the Garbage Collector runs and reclaims the memory space occupied
7 min read
Difference Between JVM and DVM
JVM is the virtual machine that runs java code on different platforms. It acts as an abstract layer between the program and the platform on which the java code is running. The portability of Java code is possible only because of the JVM. The javac compiler converts the source code file(.java file) into an intermediate java bytecode format which is
3 min read
Frequently Used JVM Parameters
A JVM or Java Virtual Machine is a software implementation of a physical machine, or we can say it is an abstract machine. Java was designed with the concept of WORA (Write Once Run Anywhere), which runs on a VM. It is a specification that gives a runtime environment during which java bytecode is often executed. The compiler compiles the Java file
3 min read
Does JVM create object of Main class (the class with main())?
Consider following program. class Main { public static void main(String args[]) { System.out.println("Hello"); } } Output: Hello Does JVM create an object of class Main? The answer is "No". We have studied that the reason for main() static in Java is to make sure that the main() can be called without any instance. To justify the same, we
1 min read
Differences between JDK, JRE and JVM
Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed in Java development. Now we need an environment to make a
5 min read
How many types of memory areas are allocated by JVM?
JVM (Java Virtual Machine) is an abstract machine, In other words, it is a program/software which takes Java bytecode and converts the byte code (line by line) into machine understandable code.  JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in Java code. JVM
3 min read
Does Garbage Collection Guarantee that a Program will not Run Out of Memory?
The work of Garbage collection in Java is to automate the process of deleting memory that's no longer in use. But does that mean Java programs are free from memory limit overflow? Well in this article we will discuss it in brief, but first, let's talk about the garbage collection in Java. Garbage Collection:In C/C++, a programmer is responsible for
3 min read
Mark-and-Sweep: Garbage Collection Algorithm
There are many garbage collection algorithms that run in the background, of which one of them is mark and sweep. All the objects which are created dynamically (using new in C++ and Java) are allocated memory in the heap. If we go on creating objects we might get Out Of Memory error since it is not possible to allocate heap memory to objects. So we
5 min read
How to Create Different Packages For Different Classes in Java?
Let us first know what is a class and package in Java. Class in java is a model for creating objects. It means that the properties and actions of the objects are written in class. Properties are represented by variables and actions of the objects are represented by methods. So, a class contains variables and methods. The same variables are also ava
6 min read
Different ways for String to Integer Conversions in Java
Given a String in Java, the task is to convert this String into Integer. Examples: Input: str = "1234" Output: 1234 Input: str = "456" Output: 456 Convert using Integer.parseInt(String) The Integer class has a static method that returns an integer object representing the specified String parameter. Syntax : public static int parseInt(String str) th
2 min read
Different Ways to Remove all the Digits from String in Java
Given alphanumeric string str, the task is to write a Java program to remove all the digit from this string and prints the modified string. Examples: Input: str = “GeeksForGeeks123”Output: GeeksForGeeksExplanation: The given string contains digits 1, 2, and 3. We remove all the digit and prints the modified string. Input: str = “12Java”Output: Java
3 min read
Different Ways to Generate String by using Characters and Numbers in Java
Given a number num and String str, the task is to generate the new String by extracting the character from the string by using the index value of numbers. Examples: Input: str = “GeeksforGeeks” num = 858 Output: GfG Explanation: The 8th, 5th, and 8th position of the characters are extracting from the given string and generate a new string. Input: s
3 min read
Different Ways To Check Java Version In Windows
Java is a programming language that is platform-independent, popular, simple, secure, and statically typed. Before discussing let's clear Java language needs a runtime platform so before going ahead let's clear how java is present on the machine. Java language comprises three components mainly: Java Development KitJava Runtime EnvironmentJava Virtu
3 min read
Different Ways to Achieve Pass By Reference in Java
There are two types of parameters one is Formal parameters and the second is Actual Parameters. Formal parameters are those parameters that are defined during function definition and Actual parameters are those which are passed during the function call in other Function. Showcasing the formal and actual parameters through code: Java Code // Java pr
5 min read
Different Ways to Prevent Method Overriding in Java
Inheritance is a substantial rule of any Object-Oriented Programming (OOP) language but still, there are ways to prevent method overriding in child classes which are as follows: Methods: Using a static methodUsing private access modifierUsing default access modifierUsing the final keyword method Method 1: Using a static method This is the first way
5 min read
Different Ways to Create the Instances of Wrapper Classes in Java
Wrapper Class a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Methods: We can use two ways to construct the instance of the Wrapper Classes Usi
5 min read
Different Ways to Copy Files in Java
There are mainly 3 ways to copy files using java language. They are as given below: Using File Stream (Naive method)Using FileChannel ClassUsing Files class. Note: There are many other methods like Apache Commons IO FileUtils but we are solely discussing copying files using java classes. Method 1: Using File Stream (Naive method) This is a naive me
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg