How Garbage Collection works in Java

I have read many articles on Garbage Collection in Java, some of them are too complex to understand and some of them don’t contain enough information required to understand garbage collection in Java. Then I decided to write my own experience as an article. You can call it a tutorial about garbage collection in simple word, which would be easy to understand and have sufficient information to understand how garbage collection works in Java. Garbage collection works by employing several GC algorithm e.g. Mark and Sweep. There are different kinds of garbage collector available in Java to collect different area of heap memory e.g. you have serial, parallel and concurrent garbage collector in Java.

A new collector called G1 (Garbage first) are also introduced in JDK 1.7.  The first step to learning about GC is to understand when an object becomes eligible to garbage collection? Since JVM provides memory management, Java developers only care about creating an object, they don't care about cleaning up, that is done by the garbage collector, but it can only collect objects which have no live strong reference or it's not reachable from any thread.

If an object, which is supposed to be collected but still lives in memory due to unintentional strong reference then it's known as a memory leak in Java. ThreadLocal variables in Java web application can easily cause the memory leak.

Important points about Garbage Collection in Java

This article is in continuation of my previous articles How Classpath works in Java and How to write Equals method in Java and before moving ahead let's recall few important points about garbage collection in Java.

1) Objects are created on the heap in Java irrespective of their scope e.g. local or member variable. while it's worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.


3) Garbage collection relieves Java programmer from memory management which is an essential part of C++ programming and gives more time to focus on business logic.


5) Before removing an object from memory garbage collection thread invokes finalize() method of that object and gives an opportunity to perform any sort of cleanup required.

6) You as Java programmer can not force garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.


8) If there is no memory space for creating a new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space

9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of ergonomics is to provide good performance from the JVM with a minimum of command line tuning. See Java Performance The Definitive Guide for more details on garbage collection tuning.

garbage collection in Java

When an Object becomes Eligible for Garbage Collection

An object becomes eligible for Garbage collection or GC if it's not reachable from any live threads or by any static references. In other words, you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as the reference so if object A has a reference to object B and object B has a reference to Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.

Generally, an object becomes eligible for garbage collection in Java on following cases:

1) All references to that object explicitly set to null e.g. object = null

2) The object is created inside a block and reference goes out scope once control exit that block.

3) Parent object set to null if an object holds the reference to another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.

4) If an object has only lived weak references via WeakHashMap it will be eligible for garbage collection.

Heap Generations for Garbage Collection in Java

Java objects are created in Heap and Heap is divided into three parts or generations for the sake of garbage collection in Java, these are called as Young generation, Tenured or Old Generation and Perm Area of the heap.  New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent minor garbage collection if an object survives its gets moved to survivor 1 and then survivor 2 before major garbage collection moved that object to old or tenured generation.

heap structure and generation in Java for GC

Permanent generation of Heap or Perm Area of Heap is somewhat special and it is used to store Metadata related to classes and method in JVM, it also hosts String pool provided by JVM as discussed in my string tutorial why String is immutable in Java. There are many opinions around whether garbage collection in Java happens in perm area of Java heap or not, as per my knowledge this is something which is JVM dependent and happens at least in Sun's implementation of JVM. You can also try this by just creating millions of String and watching for Garbage collection or OutOfMemoryError.

Types of Garbage Collector in Java

Java Runtime (J2SE 5) provides various types of Garbage collection in Java which you can choose based on your application's performance requirement. Java 5 adds three additional garbage collectors except serial garbage collector. Each is generational garbage collector which has been implemented to increase the throughput of the application or to reduce garbage collection pause times.

1) Throughput Garbage Collector: This garbage collector in Java uses a parallel version of the young generation collector. It is used if the -XX:+UseParallelGC option is passed to the runtime via JVM command line options . The tenured generation collector is same as the serial collector.

2) Concurrent low pause Collector: This Collector is used if the -Xingc or -XX:+UseConcMarkSweepGC is passed on the command line. This is also referred as Concurrent Mark Sweep Garbage collector. The concurrent collector is used to collect the tenured generation and does most of the collection concurrently with the execution of the application. The application is paused for short periods during the collection. A parallel version of the young generation copying collector is used with the concurrent collector. Concurrent Mark Sweep Garbage collector is most widely used garbage collector in java and it uses an algorithm to first mark object which needs to collect when garbage collection triggers.


An important point to note is that -XX:+UseParallelGC should not be used with -XX:+UseConcMarkSweepGC. The argument passing in the J2SE platform starting with version 1.4.2 should only allow the legal combination of command line options for garbage collector but earlier releases may not find or detect all illegal combination and the results for illegal combination are unpredictable. It’s not recommended to use this garbage collector in java.

See Java Performance by Binu John and Charlie Hunt to learn more about different JVM options and garbage collection tuning and troubleshooting.

what is garbage collector in Java

JVM Parameters for Garbage Collection in Java

Garbage collection tuning is a long exercise and requires a lot of profiling of application and patience to get it right. While working with High volume low latency Electronic trading system I have worked with some of the project where we need to increase the performance of Java application by profiling and finding what causing full GC and I found that Garbage collection tuning largely depends on application profile, what kind of object application has and what are their average lifetime etc.

For example, if an application has too many short lived object then making Eden space wide enough or larger will reduce the number of minor collections. you can also control the size of both young and Tenured generation using JVM parameters for example setting -XX:NewRatio=3 means that the ratio of the young and tenured generation is 1:3 , you got to be careful on sizing this generation.

As making young generation larger will reduce the size of the tenured generation which will force the Major collection to occur more frequently which pause application thread during that duration results in degraded or reduced throughput. The parameters NewSize and MaxNewSize are used to specify the young generation size from below and above. Setting these equal to one another fixes the young generation.

In my opinion, before doing garbage collection tuning detailed understanding of how garbage collection works in Java is a must and I would recommend reading Garbage collection document provided by Sun Microsystems for detail knowledge of garbage collection in Java. Also to get a full list of JVM parameters for a particular Java Virtual machine please refer official documents on garbage collection in Java. I found this link quite helpful though

heap regions for garbage collection in java

Full GC and Concurrent Garbage Collection in Java


Concurrent Garbage Collector in Java

Always try to avoid or minimize full garbage collection or Full GC because it affects the performance of Java application.

When you work in finance domain for an electronic trading platform and on a high volume low latency systems performance of Java application becomes extremely critical you definitely like to avoid full GC during the trading hours.

Summary on Garbage collection in Java

1) Java Heap is divided into three generation for the sake of garbage collection. These are a young generation, tenured or old generation, and Perm area.

2) New objects are created by young generation and subsequently moved to the old generation.

3) String pool is created in PermGen area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM. By the way from JDK 1.7 update, String pool is moved to heap area where objects are created.

4) Minor garbage collection is used to move an object from Eden space to survivor 1 and survivor 2 space and major collection is used to move an object from young to tenured generation.

5) Whenever Major garbage collection occurs application threads stop during that period which will reduce application’s performance and throughput.

6) There are few performance improvements has been applied in garbage collection in java 6 and we usually use JRE 1.6.20 for running our application.

7) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. The ideal ratio of this parameter is either 1:1 or 1:1.5 based on my experience, for example, you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB.

8) There is no manual way of doing garbage collection in Java, but you can use various reference classes e.g. WeakReference or SoftReference to assist garbage collector. 

That's all about garbage collection in Java. In this tutorial, we learn how the heap is divided into different regions e.g. Eden, survivor spaces, and perm gen space.  An object becomes eligible for garbage collection when there is no strong reference pointing to it or it is not reachable from any thread. When garbage collector realizes the need of garbage collection it triggers minor collection and some time stop-the-world major collection. It's all automatic as you cannot force garbage collection in Java.  


Anand said...

Nice Explanation :)


Garbage Collection Explained from the SCJP Certification Perspective

Anonymous said...


Borislav Andruschuk said...



Javin @ FIX Protocol and Electroinc Trading said...


Anonymous said...


German said...


Harish Kakumanu said...


Ramya said...



Javin said...

Hi Ramya,

Ramya said...


Javin said...

Hi Ramya,
1) different generations of heap space
2) how concurrent mark sweep garbage collection works ?

All the best for your interview :)


Ramya said...


Anonymous said...


Javin said...


Anonymous said...



2) if there is no static variable referencing object.

3) There is no object graph which is referencing the object

Javin said...


Javin said...


Roger said...


Javin @ java interview question said...


Anonymous said...


Mukesh Kumar said...

How to minimize the use of Garbage collection?

Javin @ polymorphism in java said...


Javin @ unsupportedClassVersionError in java said...


Javin @ What is abstraction in Java said...


Anonymous said...


manju said...


imran said...


Javin @ Enum examples in java said...


Anonymous said...


Lets Share said...


Anuj said...

nice article ....
But I have a question regarding it..

Javin @ Java Enum Examples said...


Javin @ String to Integer Java said...


Anonymous said...

Hi Javin, I have a doubt.


Could you please tell me where
arraylist refernce variable is kept?
where m,k is created?
where set instance in created?
where set reference variable is kept?
where i3 and i4 reference variables are created? method stack?
where string test1 and test2 are ceated?
where s and newString are created?

class A {
int m = 0;
ArrayList arrayList = new ArrayList();
static int k = 0;
static HashSet set = new HashSet ();
String s = new String("newString");

void method(){
Integer i3 = new Integer(3);
Integer i4 = new Integer(4);


Anonymous said...


Anonymous said...

Javin, also please go through

Its about method area.


Suhas said...





Javin @ String split Java said...


priya said...

hi Javin, Excellent article

Javin @ /tomcat-javalangoutofmemoryerror-permgen said...

How to increase heap size in ANT and Maven

let me know if you still have any question.

Anonymous said...


eg. String s =;
s = null;

What happens in this case?

Javin @ increase heap maven ant said...


Anonymous said...


Atul Vijay said...


Javin @ run java from command line said...


Seenu536@Varadhi said...


Javin @ increase heap maven ant said...


Javin @ iterate map in java said...


Anonymous said...


Anonymous said...

can you please elaborate on the below comment.


Anonymous said...

String s = String.valueOf(i).intern();

disha said...

I THINK......

disha said...


iRahul said...


Anonymous said...


Kim cheng said...



Vibha said...


1) Difference between Serial Garbage collector and Parallel Garbage Collector?
3) What is Garbage collection tuning ?
6) What is difference between CMS and G1 garbage collector?
7) What is Eden space in Heap?


Soumya said...


Sagar said...


Anonymous said...


Shourjya said...

I have a few questions.


Anyone is welcome with an Answer

Thanks in Advance ....

Suneel said...

Really very nice article.



Sajin Surendran said...

You have mentioned class metadat is stored perm space of heap.


So Could you please clarify


2. Whether gc occurs in method area?

Anonymous said...





Read more:

Naira Simonyan said...

Hi i have some questions related to GC

1. GC give guarantee that object will be removed ?

Thanks !

Teens said...

How many object are elligible for garbage collection for below program:

class A{

class B extends A{
public static void main(String a[]){
B b =new B();
B b1= new B();





Anonymous said...

From Java 7. String Pool is moved to the Heap.

root@boy said...

1) stop abusing the HEAP
2) stop using lesser platform like Java for critical production systems

naren said...

Calling this method suggests that the Java virtual machine expend
effort toward running the finalize methods of objects
that have been found to be discarded but whose finalize
methods have not yet been run. When control returns from the
method call, the virtual machine has made a best effort to
complete all outstanding finalizations.

Anonymous said...


Manoj Sharma said...


To read more click here

ABC said...


Anonymous said...

How long Garbage Collection takes to complete? We are seeing pause time upto 4 to 5 seconds in our Java application? is this normal? Our heap size is not very large and its somewhere around 2 to 4 GB.

Anonymous said...


For example if 10 objects are eligible for GC, then which object will get first GC? in what basis it will assign.


charitha nagella said...

I have one doubt. I am beginner.I am not understood if Object A has reference of object B and object B has reference of Object A then how both Objects A and B will be eligible for Garbage collection?
Ex:If we take Some class like

S a=new S();
S b=new S();
S t=b;
Still a pointing b and b pointing a. Then how a and b both eligible for garbage collection? I am not understood please help me.

Manish Sahu said...

What is the use of gc() method if there is no guarantee of garbage collection ?
in which condition we should call it ?

Javin Paul said...

@Manish Sahu, its not guaranteed but it does cleanup every time you call it. What Java tells you that you cannot build your solution based upon that method, garbage collection should be left to Garbage collector. If you use Eclipse, you can see that GC collector icon at bottom right, that use this method to run GC and free memory.

Anonymous said...

Hi, I would really appreciate if someone will explain how the concepts above changed since Java 8 introduced Metaspace instead of the PermGen.

Anonymous said...

How does Java Garbage Collection work? Short answer: it doesn't. EVER.

Anonymous said...

I was looking for a tool that can help me to understand the GC log in a graphical way and this tool has given the exact functionalities that I was looking for.

Post a Comment