Java Garbage Collection. Practical :Visual VM

I wanted to see how garbage collections work. but all i can find was theory and theory. Thus thought to try it out with a very basic program to see it practically.

Some basic information that one should know.

1 Eden Space : All the new objects that are created goes to this part of heap

2 Survivor Spaces (S0/S1) : After minor GC reachable object from the Eden space and from one part (S0/S1) of the survivor space is transferred to another part of survivor space (S0/S1). And with this the age of each surviving object is incremented.

3 Old Generation Space : An object can reach here by two ways. One if the max age of the object is reached other when there is memory overflow in survivor space memory.

You might understand better reading these articles, I also studied this stuff from here

So now i tried to make it practical and created this basic java program.

Now to visualize the memory spaces there are many tools but i used Visual VM

So basically this program keeps creating objects and keeps filling the eden/survivor/tenured spaces.

I was just focussing on filling these memory spaces and according to my knowledge , these A class objects are not eligible for garbage collection at any point of time.

So running this program normally wont give you much visual information as the memory of these object is very low thus we need to set the maximum heap size to a very low value explicitly. Small as 2MB.

so we need to run the program as simply as this

java -Xmx2m Test

When you run visual VM with this it would look like.


I would continue to run more scenarios of garbage collection, and will share soon.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store