Mark and Sweep
- During the “Mark” process, the garbage collector looks through the memory space and mark the ones that are being referenced by either stack variables or static variables.
- During this “Mark” process, the application itself is being paused, which is called “Stop the world”. If there’s any other threads running, the Marking process would work.
- During the “Sweep” process, the garbage collector looks through the Heap space and frees up the memory that are not marked from the “Mark” step.
- Then, the “Marked” objects are moved to a single contiguous block of memory, which prevents the Heap from being fragmented over time. And this makes it easier and quicker for the virtual machine to find memory to allocate future objects.
Young Generation, Old Generation
As looking through the whole Heap space would take time, Heap space is divided into two different sections, which is called the Young Generation(Eden, Survival 0, Survival 1) and the Old Generation.
Garbage collections happening from Young Generation is called as Minor GC, while the ones happening from Old Generation is called as Major GC or Full GC.
As the space of the Old Generation is much bigger and there is likely to be more objects that are still being referenced in the Old Generation, the Major GC process usually takes longer, which means the Minor GC is much efficient.


Process of Garbage Collection



In the meantime, the newly created objects will be created under the Eden area again.


Step 2~5 will repeat and the Young Generation area will be used in turn.
(The number itself on the Survival area doesn’t mean anything. Not related to any priority)

MaxTenuringThreshold), it’ll be moved to Old Generation area. 
As seen from the process of “Mark and Sweep”, only the 2 out of 3 sections of Young Generations will be used.
When the GC happens on Eden and S0 area, the marked objects will be moved to S1 area into a single contiguous block.
Then, when the GC happens on Eden and S1 area, the marked ones will be moved to S0 area.
The S0 and S1 area will be full in turn.
With that being said, not 100% of the Young Generation will be used, either S0 or S1 will always be empty.

Leave a comment