Tuesday, December 4, 2018

Java Crash Course : Garbage Collection

In Languages like C, C++ it is the responsibility of the developer to allocate/deallocate the memory needed for a program using malloc and calloc commands.

In Java, it is done by Java virtual machine automatically using the Garbage collector. In general, any object on the heap which cannot be referenced from the stack is eligible for garbage collection.

Garbage Collection uses two strategies to clear the heap.

  1. Match and sweep - Instead of identifying the objects with no references, GC maps all the objects for which there is a reference from the stack and sweeps others.
  2. Generation Collection - It was discussed as part of Java Memory management crash course where the heap is divided into four sections. Objects from the young generation are swept more than the objects in the old generation.

Java Crash Course : Memory Management in JVM

This document holds the summary of memory management concepts in JVM (Java Virtual Machine) that every software engineer should be aware of while designing/coding in Java.

Memory is divided into 2 parts
  1. Stack 
  2. Heap

Stack : Small when compared to heap memory and stores local variables and references to the objects in Heap.

  1. Each thread has its own Stack.
  2. Shorter life span
  3. Data from Stack is removed as soon as close braces ( } ) is encountered.
  4. Primitive types are saved in Stack.
  5. If a method pushed 10 elements to the Stack, all the 10 will be removed upon encountering closing braces.