Garbage Collection in Java

Back to home
Logicmojo - Updated Aug 28, 2021

What is Garbage Collection?

The method through which Java programs do automatic memory management is known as garbage collection. Java applications are compiled into bytecode that a Java Virtual Machine, or JVM, may run. Objects are created on the heap, a section of memory dedicated to the Java application while it is running on the JVM. Over time, some objects will become obsolete. The garbage collector discovers these unneeded things and deletes them to free up memory.

A programmer in C/C++ is in charge of both the creation and destruction of objects. The deletion of unneeded objects is usually overlooked by programmers. Because of this carelessness, sufficient memory may not be available to construct new objects at some time, and the application will end abnormally, resulting in OutOfMemoryErrors.

In Java, however, the programmer does not have to worry about things that are no longer in use. These items are disposed of by the garbage collector. Garbage Collector's principal goal is to clear heap memory by eliminating unreachable items. Because it is continually operating in the background, the garbage collector is the greatest illustration of the Daemon thread.

How Does Garbage Collection in Java works?

In Java, garbage collection is a completely automated process. Automatic garbage collection is the process of examining heap memory, determining which things are in use and which are not, and eliminating the latter. An in-use object, also known as a referred object, signifies that it is still referenced by some portion of your application. Any section of your programme no longer refers to an unused or unreferenced object. The memory of an unreferenced object can thus be reclaimed. The programmer does not need to explicitly mark things to be destroyed. The JVM is where garbage collection is implemented.

Garbage collection is implemented in the JVM. Each JVM is free to implement garbage collection in whatever way it sees fit, as long as it adheres to the JVM standard. Despite the fact that there are other JVMs, Oracle's HotSpot is by far the most popular. It has a well-developed set of garbage collecting options.

Despite the fact that HotSpot offers a variety of garbage collectors suited for different use cases, they all follow the same basic approach. Unreferenced objects are identified and marked as garbage collection ready in the first stage. Marked objects are eliminated in the second phase. After the garbage collector deletes items, memory can optionally be compacted so that the remaining objects are in a contiguous block at the heap's start. After the block of memory allocated to existing objects, the compaction procedure makes it easier to allocate memory to new objects sequentially.

All of HotSpot's garbage collectors use a generational garbage collection method, which divides objects into groups based on their age. The idea behind generational garbage collection is that most objects have a short lifespan and will be ready for waste collection soon after they are created.

There are three sections to the heap:

  1. Young Generation: The Young Generation is where newly generated objects begin. The Young Generation is further separated into an Eden area, which is where all new items begin, and two Survivor spaces, which are where objects are transported from Eden after one garbage collection cycle. It is a minor waste collection event when objects from the Young Generation are collected.

  2. Old Generation: Long-lasting items are eventually passed down from the Young Generation to the Old. When items from the previous generation are gathered, it is a massive garbage collection event.

  3. Permanent Generation: The Permanent Generation is where metadata like classes and methods are saved. Garbage collected from the Permanent Generation may include classes that are no longer in use.

Unused objects from all generations are rubbish collected during a full garbage collection event.

There are four garbage collectors in HotSpot:

  1. 1. Serial: In a single thread, all trash collection events are carried out sequentially. After each waste collection, compaction is performed.

  2. 2. Parallel: For minimal garbage collection, many threads are used. For large garbage collection and Old Generation compaction, a single thread is employed. The Parallel Old version, on the other hand, uses multiple threads for substantial trash collection and compaction of the Old Generation.

  3. 3. CMS (Concurrent Mark Sweep): The same approach as Parallel is utilised to use many threads for modest garbage collection. Although major garbage collection, such as Parallel Old, is multi-threaded, CMS works concurrently with application processes to avoid "stop the world" occurrences (i.e. When the garbage collector is active, the application is terminated). There will be no compaction.

  4. 4. G1 (Garbage First):

    The new garbage collector is meant to take the role of CMS. It's parallel and concurrent, much like CMS, but it's a lot different underneath the hood than older trash collectors.

How to Dereference an Object in Java

Garbage Collection's main goal is to free heap memory by deleting items that don't have a reference. When an object has no references, it is thought to be dead and no longer required. As a result, the object's memory can be reclaimed.

The references to an object can be released in a variety of ways, making it a candidate for Garbage Collection. Here are a few examples:

By making a reference null

Student student = new Student();
student = null;

By assigning a reference to another

Student studentOne = new Student();
Student studentTwo = new Student();
studentOne = studentTwo; // now the first object referred by studentOne is available for garbage collection

By using an anonymous object

register(new Student());

What are the Java Garbage Collection Roots?

Garbage collectors use the concept of Garbage Collection Roots (GC Roots) to determine which things are alive and which are dead.

The following are some examples of Garbage Collection roots:

  1. The system class loader loads the classes (not custom class loaders)

  2. Threads in progress

  3. The currently performing methods' local variables and parameters

  4. JNI methods' local variables and parameters

  5. JNI reference at a global level

  6. Objects that serve as synchronisation monitors

  7. JVM keeps objects from trash collection for its own needs.

Beginning with those Garbage Collection Roots and tracing references from the roots to other objects, the garbage collector traverses the whole object graph in memory.

Advantages of Garbage Collection

The following are some of the advantages of using Garbage Collection in Java:

  1. The garbage collector removes unreferenced objects from heap memory, which makes java memory efficient.

  2. We don't need to do anything because the garbage collector (part of the JVM) does it for us.

With this article at Logicmojo, you must have the complete idea of Garbage Collection in Java