Lecture 4 Garbage Collection
Lecture 4 Garbage Collection
CIC-212
Java Programming
Lecture 4
Young Generation
Young generation memory consists of two parts, Eden space and survivor
space. Shortlived objects will be available in Eden space. Every object starts its
life from Eden space. When GC happens, if an object is still alive then it will be
moved to survivor space and other dereferenced objects will be removed.
5
Java Garbage Collection Process
Old Generation: Old or tenured generation
is the second logical part of the heap
memory. When the garbage collector does the
minor GC cycle, instances that are still live in
the S1 survivor space will be promoted to the
old generation. Objects that are dereferenced
in the S1 space is marked for eviction.
6
Java Garbage Collection Process
7
Java Garbage Collection Process
Finalization of Instances in
Garbage Collection
Just before evicting an instance and
reclaiming the memory space, the Java
garbage collector invokes
the finalize() method of the respective
instance so that the instance will get a
chance to free up any resources held by it.
8
Example Program for GC
OutOfMemoryError
Garbage collection does not guarantee safety from out of memory issues. Mindless code
will lead us to OutOfMemoryError.
import java.util.LinkedList;
import java.util.List;
public class GC { public static void main(String[] main)
{
List l = new LinkedList(); // Enter infinite loop which will add
a String to the list: l on each // iteration.
do { l.add(new String("Hello, World")); }
while (true); } }
Output: