Image for post
Image for post

Introduction to Garbage Collection

Yusuf Çakal
Apr 5, 2019 · 2 min read

Garbage Collection is a mechanism provided by Java Virtual Machine. All garbage collection algorithms run/process in the background. We will take a look at one of those algorithms bellow.

Why is there garbage collector and what is it doing on JVM?

Memory Management

First of all, developers who wrote C or C++ in the past may remember malloc and free functions. malloc function provides memory allocation, free function frees the memory space. However there is it who does this instead of us in JVM.

The fundamental task of the garbage collector is memory management and reclaim to heap space which eligible objects. Java developers only care about creating objects. They don’t care about cleaning up. In java there are methods like System.gc() and Runtime.gc() which can be used to request of garbage collector from JVM. But it’s not guaranteed that garbage collection will happen.

There are many garbage collection algorithms which run in background. One of them is “Mark and Sweep”.

Mark, Sweep and Compaction

The algorithm basically performs two operations to relieve memory. All objects has own their mark bit.

First operation detects unreachable objects in the heap.

Second operation cleans the detected objects.

Let’s focus on the details

Mark Phase

In the mark phase set mark bits to all objects. When an object is created mark bit is set to false(0), and other all reachable objects are set to true(1). In the bellow image you can see six objects in the heap. Those four objects can refer to each other. So their mark bits are set to true(1). The mark bits are set false(0) for other objects.

Sweep and Compaction Phases

Sweep phase means cleaning up objects that unreachable in the memory. After the sweep operation starts compaction. The garbage collector simply updates any object reference and re-point them to moved objects.

I tried explain in a simple way, next story can be about analyzing memory by JProfiler. You can leave comment at 👇 if you couldn’t understand anything about this.

Thanks to Ufuk Uzun and M. Kerem Keskin for review and valuable informations 😊

Dolap Tech — Elden ele teknoloji!

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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