What is Garbage Collection? How does it work?

Garbage collection is the process of reclaiming unused memory through the destruction of unused objects. In the languages like C and C++, the programmer is responsible for the creation and destruction of objects. In some cases, the programmer may forget to destroy the useless memory and the memory allocated to them is not released. The used memory of the system keeps on growing, and there might be no memory left to allocate. In such cases, the applications suffer from memory leaks.

After a certain point, sufficient memory may not be available for the creation of new objects. In such cases, the entire program gets terminated abnormally due to out-of-memory errors.  You can use methods like free() in C and delete in C++ to perform garbage collection. In Java, garbage collection happens automatically during the life cycle of the program. This eliminates the need to deallocate memory and therefore avoid memory leaks. Here you can use methods like free() in C Language and delete() in C++ to perform the garbage collection. In Java, garbage collection happens during the lifecycle of the program. This eliminates the need to deallocates the memory as well as the memory leaks.

Are you new to the concept of JAVA, If so, check out What is JAVA?

Garbage Collector in JAVA:

The process of automatic memory allocation by java programs is known as Java Garbage Collection. JAVA program compiles into bytecode, that can run the JAVA Virtual Machine (JVM). When the JAVA program runs on JVM, objects were created on the heap, which creates a portion of memory to the program.  Over the lifetime of the application, new objects were created and released. Here heap consists of two types of objects:

Live – Objects are being used and referenced from somewhere else

Dead – These objects were no longer used (or) reference from anywhere

Garbage Collector Silent Features:

  • It is controlled by a thread known as Garbage Collector
  • JAVA provides two methods gc() and Runtime.gc() that sends a request to JVM for garbage collection.
  • JAVA programmers are free from memory management. Programmers cannot force the garbage collector to collect the garbage it depends on JVM
  • When the garbage collector removes the object from the memory, initially the garbage collector thread () calls the finalize () of the object and then remove it.

Object Allocation:

When an object allocates, the Jrocket JVM checks the size of the object. It distinguishes between small and large objects. Here the small, as well as the large size, depends on heap size, JVM Version, Garbage collection strategy, and the platform used. The actual size of the object varies from 2KB to 128KB.

The small objects here were stored in a Thread Local Area (TLA) which is a free chunk of the heap. If the thread is using the young space, it is directly stored in the old space. Here the large object requires more synchronization between the threads.

When is an object eligible for Garbage Collection?

An object becomes eligible only if it is not used by any program (or) thread (or) any static references. If two objects having a reference to each other and do not have any live reference, then the objects are collected by the garbage collector. There are some other cases where an object is eligible for garbage collection,

  • If the reference of the object is set to null
  • An object is created inside the block and the scope goes out of the scope.

How does JAVA Garbage Collector in JAVA work?

JVM Controls JAVA Garbage collector. JVM decides when to perform the Garbage collection.  You can also request JVM to run the garbage collector. But there is no guarantee that JVM will compile in all conditions. JVM runs the garbage collector if it senses that the memory is running low. When the JAVA program requests the garbage collection, JVM usually accepts it in short order. But it doesn’t make sure that the request has been accepted.

Do you want to know the practical working of JAVA Garbage Collector? If yes, visit JAVA Online Training

Which method is used for garbage collection?

In JAVA, every program has more than one thread and every thread has its execution stack. The main() method contains a thread that is responsible for running a JAVA program. If no live thread is accessing the garbage collector, then-current the thread will access the garbage collector. Once accessed, the garbage collector considers the object is eligible for deletion. If the program has a reference variable that references the object, that reference variable available to the live thread is known as reachable.

Usually, the garbage collection happens to the memory when the object is no longer needed. Even though JAVA programming contains many live objects, garbage collection does not guarantee that there is enough memory. Java compiler usually maintains the enough memory

Types of Garbage Collection:

Serial GC: It uses the mark and sweeps approach for the young and old generations. i.e minor and major Garbage Collections

Parallel GC: It is similar to the serial GC except, it spawns N threads for young generation garbage collection.

Parallel Old GC: It uses multiple threads in both generations and the rest is similar to the parallel GC

G1 Garbage collector: It is introduced in JAVA 7. Its main objective is to replace the CMS collector. It’s a parallel, concurrent well as the CMS collector. Here, there is no young and the old generation space. Here the heap is divided into different equal-sized heaps which collects the regions with lesser live data.

Concurrent Mask Sweep Collector: It does the garbage collection for the old generation. Here through XX: ParallelCMSThreads = JVM option you can limit the number of threads in the CMS collector. Some people also call it a concurrent Low Pause Collector.

Mark and Sweep Algorithm:

JRockit uses the mark and sweeps algorithm for garbage collection. It contains two phases namely the mark phase as well as the sweep Phase.

Mark Phase: This phase makes the objects accessible from various sources like native handles, threads and other GC root sources and marks them as alive. Every object tree has more than one root object where the GC root is always reachable. So any object that has a garbage collection at its root identifies and marks all the objects that are in use and the rest were considered as garbage.

Sweep Phase: This phase finds the gaps between the objects by reversing the heap. The free list present here records the gaps and is made available for new object allocation.

JVM perform the garbage collection through this process and has the following pros and cons:

Pros:

  • It's an infinite loop
  • It’s a recurrent process
  • No additional overhead during the algorithm execution

Cons:

  • Cannot run the normal program parallelly
  • Runs multiple times on a program

We cannot find a process with no cons. Every program has an equal number of pros and cons. Keeping the cons aside Garbage collection is the best process in programming languages like JAVA. But this concept is very good at memory deallocation. You can grab practical knowledge on garbage collection from Real-time professionals through JAVA Online Course. Additionally, you can also check out the JAVA Interview Questions prepared by real-time professionals to get placed in MNC’s