Showing posts with label Java Heap memory. Show all posts
Showing posts with label Java Heap memory. Show all posts

Wednesday, December 28, 2016

Java garbage collection

Java garbage collection is an automatic process to manage the runtime memory used by programs. So, the programmer don't have any overhead of assigning and freeing up memory resources in a program itself. Being an automatic, programmers need not to initiate the garbage collection process from the code. Still programmers use System.gc() and Runtime.gc() to the JVM to initiate the garbage collection process. But this is depends on the JVM. Because the JVM may reject the request. This decision is taken by the JVM based on the eden space availability in heap memory. So there is no guaranteed that the above calls perform the garbage collection. 

Eden Space
When an instance is created, it is first stored in the eden space in young generation of heap memory area. 

Survivor Space (S0 and S1)
For the minor garbage collection cycle, objects that are live (which is still referenced) moved from Eden space to Survivor space S0. Like that garbage collector scans S0 and move the live objects to the S1. The objects that are not referenced are marked for the garbage collection.

Old Generation
Old generation is the second logical part of the heap memory. When the garbage collector perform minor GC, objects that are still live in the Survivor space S1 are moved to old generation. Objects that are no longer referenced in the Survivor space S1 are marked for removal.

Major GC
Old generation is the last phase in the life cycle of objects with respect to the garbage collection process. While performing major GC, garbage collector scans the old generation part of the heap memory. If the objects are no longer referenced, they are marked for removal. If not they will stay in the old generation.

Java Heap Memory

At runtime the Java instances are stored in the heap memory. When an object is no longer referenced it becomes deserved for removal from heap memory. During garbage collection process, those objects are removed from heap memory and the space is reclaimed. Heap memory has three major areas,
  1. Young Generation
    1. Eden Space (any instance enters the runtime memory area through eden)
    2. S0 Survivor Space (older instances moved from eden to S0)
    3. S1 Survivor Space (older instances moved from S0 to S1)
  2. Old Generation (instances promoted from S1 to tenured)
  3. Permanent Generation (contains meta information like class, method detail)