Learn more about the Garbage Collector in Java, how it works, and the various types of GC available in Java and their advantages. Java Garbage Collection is the process by which Java programs perform automatic memory management. Java programs compile into bytecode that can be run on a Java Virtual Machine (JVM).

In my previous article, I wrote about the Java Virtual Machine (JVM) and explained its architecture. As part of the Execution Engine component, I also briefly covered the Java Garbage Collector (GC).

In this article, you will learn more about the Garbage Collector, how it works, and the various types of GC available in Java and their advantages. I will also cover some of the new experimental Garbage Collectors that are available in the latest Java releases.

What is Garbage Collection in Java?

Garbage Collection is the process of reclaiming the runtime unused memory by destroying the unused objects.

In languages like C and C++, the programmer is responsible for both the creation and destruction of objects. Sometimes, the programmer may forget to destroy useless objects, and the memory allocated to them is not released. The used memory of the system keeps on growing and eventually there is no memory left in the system to allocate. Such applications suffer from “memory leaks”.

After a certain point, sufficient memory is not available for creation of new objects, and the entire program terminates abnormally due to OutOfMemoryErrors.

You 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.

Java Garbage Collection is the process by which Java programs perform automatic memory management. Java programs compile into bytecode that can be run on a Java Virtual Machine (JVM).

When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program.

Over the lifetime of a Java application, new objects are created and released. Eventually, some objects are no longer needed. You can say that at any point in time, the heap memory consists of two types of objects:

  • Live - these objects are being used and referenced from somewhere else
  • Dead - these objects are no longer used or referenced from anywhere

The garbage collector finds these unused objects and deletes them to free up memory.

#java #programming #developer

Garbage Collection in Java – What is GC and How it Works in the JVM
1.75 GEEK