mark and sweep alog
We often talk about Garbage Collector in Java. Garbage Collector work based on Mark and sweep algorithm.

What is Automatic Garbage Collection? And how it works ?

Interview questions on garbage collector java, very important questions on garbage collector, garbage collection in java, interview questions on garbage collector.mark and sweep algorithm.

Garbage collection is process of looking at heap memory, identify unused memory and clean that memory. In older languages like C we was manually deleting unused objects to clean the memory.
In Java, process of deallocating memory is handled automatically by the garbage collector. The basic process can be described as follows. Java use mark and sweep algorithm for garbage collection.
The algorithm can be expressed as follows:

for each root variable r
mark (r);
sweep ();

It has mainly two phases.

1. Mark

This is first step of mark and sweep algorithm. In this we search all unused objects and mark them to delete.
In order to distinguish the live objects from garbage, we record the state of an object in each object. That is, we add a special Boolean field to each object called, say, marked. By default, all objects are unmarked when they are created. Thus, the marked field is initially false.
An object p and all the objects indirectly accessible from p can be marked by using the following recursive mark method:

void mark (Object p)

if (!p.marked)

p.marked = true;
for each Object q referenced by p
mark (q);

Notice that this recursive mark algorithm does nothing when it encounters an object that has already been marked. Consequently, the algorithm is guaranteed to terminate. And it terminates only when all accessible objects have been marked.

2. Sweep

In the second phase, the garbage collection algorithm scans through the heap and reclaims all the unmarked objects.
In its second phase, the mark-and-sweep algorithm scans through all the objects in the heap, in order to locate all the unmarked objects. The storage allocated to the unmarked objects is reclaimed during the scan. At the same time, the marked field on every live object is set back to false in preparation for the next invocation of the mark-and-sweep garbage collection algorithm:

void sweep ()

for each Object p in the heap

if (p.marked)
p.marked = false
heap.release (p);
The following two tabs change content below.
He is founder and CTO of He senior software architect. He is guru of various Mobile and web technologies including Node.js, Angular.js, Meteor.js. He is founder member of habilelabs Pvt. Ltd.