Garbage Collection in Java

Memory leak is one of the worst problems in programming languages. It is the situation in which objects that are no more useful and not freed continue to consume memory. In languages like C there are mechanism through which the programmer can free the memory. But in Java, the JVM will control the memory management without much programmer involvement. Garbage collection is a mechanism that was introduced in List language and later adopted in Java. It is daemon thread for automatic memory management in Java.

Objects are allocated in the heap memory of JVM and there should be corresponding references present in the stack for the heap object. In any programs most objects are soon become unreachable after there creation. Garbage objects are the objects that is no more requires for the program execution. Garbage collector (GC) searches for unreachable objects in the heap. Any objects in the heap, which cannot be reached through a reference from a stack is eligible for garbage collection.

There are two phases in GC Algorithm.

Mark: GC searches through the heap and marks the objects that should me retained.

Sweep: Objects not marked are removed from the memory and do the memory de-fragmentation (compacting).


JVM heap space is divided into two: Young generation space and Old generation space. Young generation space is further divided into Eden space, Survivor space 1 and Survivor space 2. New objects are created in the Eden space. There are two phases of GC: minor GC and major GC. Minor GC runs through the young generation space. In the first run of minor gc, live objects from the Eden space will be moved to the survivor space 1 and unreachable objects will be removed. In the second run of the minor GC, live objects will be moved to survivor 2 from survivor 1 and will remove unreachable objects. In the subsequent runs of the minor GC the reachable objects will be swapped between survivor 1 and survivor 2. If any object survived threshold number of minor GC (usually 8), it will be moved to the old generation space. If the old generation gets full, then the major GC will be performed across the entire heap (both young and old generation).

There are mainly 3 types of JVM Garbage Collectors are present. They are,

  1. Serial GC : Single threaded GC

  2. Parallel GC: Multithreaded GC

  3. Mostly Concurrent GC: Application is not paused while performing sweeping, but need to pause while marking. Eg: Concurrent Mark Sweep GC, G1 GC.