Understand Garbage Collection in java
Tags: java, memorymanagement, programming, coding
Published: 2019-07-16 16:47:40

---
title:Understand Garbage Collection in java
published: true
description: 
tags: #java #memory_management #programming #coding
---
In this post, we will see about Garbage Collection in <a href="https://java2blog.com/core-java-tutorial-for-beginners-experienced/" target="_blank" rel="noopener">java</a>.

I will try to explain with the help of diagrams and examples rather than theory.

JVM Memory is divided into three parts
<ul>
 	<li>Young generation</li>
 	<li>Old generation</li>
 	<li>Metaspace (Perm Gen)</li>
</ul>

<hr />

<h2><span style="color: #800000;">Young Generation</span></h2>
As the name suggests, young generation is the area where newly created <a href="https://java2blog.com/object-class-java/" target="_blank" rel="noopener">objects</a> are allocated.
<ul>
 	<li>When young generation fills up, it cause minor garbage collection aka Minor GC.</li>
 	<li>When minor Gcs occurs, dead objects will be removed from young generation.</li>
 	<li>If you have lot of dead objects in young generation, Minor GC will be perfomed faster.</li>
 	<li>All minor GCs are "stop the world" events, so when minor GCs occurs, application threads will also stop.</li>
</ul>
Let's understand more about how objects are allocated in Young generation.

Young generation is divided into 3 parts.
<ul>
 	<li>Eden space</li>
 	<li>Survivor space S0</li>
 	<li>Survivor space S1</li>
</ul>
Here is illustration of the young and old generation.
<img class="aligncenter size-large wp-image-7482" src="https://java2blog.com/wp-content/uploads/2019/05/YoungOldGeneration-1024x733.png" alt="YoungOldGeneration" width="530" height="379" />
<ul>
 	<li style="list-style-type: none;">
<ul>
 	<li>All newly created objects are allocated in eden space.</li>
 	<li>When Eden space is completely filled with objects then minor GC will occur. All the objects which are not dead or unreferenced will be moved to one of the survivors spaces. In our case, let's say all the objects are moved to S0.</li>
</ul>
</li>
</ul>
<img class="aligncenter size-large wp-image-7649" src="https://java2blog.com/wp-content/uploads/2019/07/EdenToS0ObjectsAllocation.jpg" alt="" width="660" height="490" />
<img class="aligncenter size-full wp-image-7648" src="https://java2blog.com/wp-content/uploads/2019/07/S0AllocatedObjects.jpg" alt="S0AllocatedObjects" width="660" height="490" />
<ul>
 	<li style="list-style-type: none;">
<ul>
 	<li>When Eden space is filled again, then all the live objects in Eden space andSurvivor space S0 will be moved to Survivor space S1.</li>
</ul>
</li>
</ul>
<img class="aligncenter size-large wp-image-7653" src="https://java2blog.com/wp-content/uploads/2019/07/S0T0S1AlloactedObjects.jpg" alt="S0T0S1AlloactedObjects" width="660" height="490" />
<img class="aligncenter size-full wp-image-7652" src="https://java2blog.com/wp-content/uploads/2019/07/S1AllocatedObjects.jpg" alt="S1AllocatedObjects" width="660" height="490" />
<ul>
 	<li>Once objects are survived multiple cycles of minor GC, they will be moved to old generation. You can control this threshold by MaxTenuringThreshold. The actual tenuring threshold is dynamically adjusted by JVM.</li>
</ul>
Let's try to demonstrate this behavior with the help of example:
You have below class in which I am creating short-lived objects for demonstration.
<pre class="“java”" name="code">package org.arpit.java2blog;

import java.math.BigDecimal;

public class GCCollectorExample {
	public static void main(String args[])
	{
		createObjects();
	}
	private static void createObjects() {

		long count = 0;
		
		while(true) { 
			// Creating short-lived objects just for illustration
			BigDecimal shortLivedBigDecimal1 = new BigDecimal(count++);
		}
	}
}
</pre>
When you run the program. Let's check memory allocation in Visual GC (A visualVM plugin)

<img class="aligncenter wp-image-7658" src="https://java2blog.com/wp-content/uploads/2019/07/S0AndEdenDemonstation-1024x422.png" alt="S0AndEdenDemonstation-1024x422" width="700" height="289" />
As you can see, we have few objects in S0 and once eden space is completely filled, all referenced objects will be moved to S1.

<img class="aligncenter wp-image-7657" src="https://java2blog.com/wp-content/uploads/2019/07/S1FilledAndEdenDemonstration-1024x424.png" alt="S1FilledAndEdenDemonstration" width="700" height="290" />

<hr />

<h2><span style="color: #800000;">Old generation</span></h2>
<ul>
 	<li>It is used to hold old long surviving objects</li>
 	<li>It is generally larger than the young generation.</li>
 	<li>When tenured space is completely filled(or predefined threshold) with objects then Major GC will occur. It will reclaim the memory and free up space.</li>
 	<li>Often, Major GCs are slower and less frequent than minor GC.</li>
</ul>
<strong>How can you use this information to optimize memory?</strong>
It depends on nature of application.
If you have lots of temporary objects then there will be lot of minor gc. You can provide arguments XX:NewRatio=1 to distribute 50% to young generation and 50% to old.
By default, NewRatio=2 hence young Generation is 1/3 of total heap.
Similarly, If you have too many long-lived objects, then you might need to increase size of tenure space by putting high value of NewRatio.
<h3>Why two survivor spaces?</h3>
You must be wondering why do we have 2 survivor space. We have 2 survivor spaces to avoid memory fragmentation. Each time you copy objects from eden to survivor and you get empty eden space and 1 empty survivor space.

<hr />

<h2><span style="color: #800000;">Garbage Collection Algorithms</span></h2>
JVM comes with several algorithms for young and old generation. There are 3 types of algorithms
<h3>serial collector</h3>
It uses single thread to perform all the garbage collection and is suitable for basic application with single processor machines.

<img class="aligncenter size-full wp-image-7665" src="https://java2blog.com/wp-content/uploads/2019/07/SerialGC.jpg" alt="SerialGC" width="357" height="291" />
<h3>Parallel collector</h3>
It uses multiple CPUs to perform garbage collector. While serial collector uses 1 thread to perform GC, parallel GC uses several threads to perform GC and it is useful when there is enough memory and good number of cores.

<img class="aligncenter size-full wp-image-7664" src="https://java2blog.com/wp-content/uploads/2019/07/parallelGC.jpg" alt="ParallelGC" width="358" height="291" />
<h3>Concurrent collector</h3>
Concurrent collector performs garbage collection with application threads. It is useful for applications which have medium to large datasets and require quick response time.

<img class="aligncenter size-full wp-image-7663" src="https://java2blog.com/wp-content/uploads/2019/07/concurrentGC.jpg" alt="concurrentGC" width="415" height="291" />

You can use different GC algorithms for young and old generations but you can pair only compatible algorithms.

For example: You can not pair Parallel Scavenge for young generation to Concurrent mark sweep for old as parallel scavenge does not provide synchronization which is required in CMS.

Here are garbage collectors which you can use for young and old generation.
[table id=17 /]

There are a lot of changes in garbage collectors after<a href="https://java2blog.com/java-8-tutorial/" target="_blank" rel="noopener"> Java 8</a>, I will try to cover them in my next articles.

If you have any suggestions on this article, please comment.
<strong>Original post:</strong> 
<a href="https://java2blog.com/garbage-collection-java/" target="_blank" rel="noopener">Garbage Collection in java</a>
<div>You may also like:</div>
<ul>
<li><a href="https://java2blog.com/core-java-tutorial-for-beginners-experienced/" target="_blank" rel="noopener">Core java tutorial</a></li>
 	<li><a href="https://java2blog.com/introduction-to-spring-framework/" target="_blank" rel="noopener">Spring tutorial</a></li>
 	<li><a href="https://java2blog.com/spring-mvc-tutorial/" target="_blank" rel="noopener">Spring MVC tutorial</a></li>
 	<li><a href="https://java2blog.com/spring-boot-web-application-example/" target="_blank" rel="noopener">Spring boot web application example</a></li>
 	<li><a href="https://java2blog.com/spring-boot-hibernate-example/" target="_blank" rel="noopener">Spring boot hibernate example</a></li>
 	<li><a href="https://java2blog.com/spring-boot-interview-questions/" target="_blank" rel="noopener">Spring boot interview questions</a></li>
 	<li><a href="https://java2blog.com/spring-interview-questions-and-answers/" target="_blank" rel="noopener">Spring interview questions</a></li>
</ul>