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?
First of all, developers who wrote C or C++ in the past may remember
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
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.