The garbage collector is a program which runs on the Java Virtual Machine which is responsible for allocating and reclaiming the memory for running java applications. The objects which are not being used by a Java application or not accessible by any live thread anymore that would be eligible for garbage collection and it's memory will be reclaim by garbage collector. GC does memory management automatically.
How to invoke garbage collector explicitly in java code?
island of isolation in GC
Java Memory Management
Garbage Collection of Young-Generation
When Garbage collector runs all the referenced objects in Eden-Space and From-Survivor are copied into the To-Survivor. During this operation the objects that already have been kept from some time in the Survivor spaces are moved into the Old-Generation
After that Eden-Space and From-Survior are emptied while From-Survivor and To-Survivor spaces switch their functions.So during this some objects are fit into From-Survivor and other objects are directly moved into the Old-Generation. After garbage collection of the Young-generation is finished both
Eden-Space and To-Survivor are empty.
Please refer below diagram:-
Garbage Collection of Old-Generation
In order to reclaim the memory from Old-Generation and Perm-Generation generally mark-sweep-compact algorithm is used. During the mark phase
all the objects that are reference by active objects (for example active thread objects, system classes, local variables, pending exceptions, references of native stack). The
removal of objects take place in the sweep phase. After completion of sweep phase the markings are removed. The memory is now fragmented. During the compaction phase
all the remaining objects are moved to the beginning of the generation in order to get a continuous free memory region. This simplify the allocation of memory for new objects.