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.
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.
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 else heap.release (p);
Latest posts by Shankar Morwal (see all)
- Upgrade node.js version in ubuntu 14 or ubuntu 16 - May 8, 2017
- Angular 4 will be out soon, Everything you need to know - February 20, 2017
- Installing teamcity 10.0.4 on ubuntu server - January 17, 2017