Garbage Collector
Garbage Collector
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
1) By nulling a reference:
3) By annonymous object:
1. new Employee();
The Algorithm
The garbage collection algorithm performs the following two basic tasks:
Detection of the eligible object is done by defining a set of roots and tracing the reachability
from the roots. An object is said to be reachable if there exists a path of reference from the
roots using which the executing program can access the object. These roots once defined
are accessible to the executing program. An object which is reachable from any of these
roots is considered to be "live." Objects that are not reachable by the defined roots are
considered to be garbage, as they cannot put any impact on the execution of the program
further. In addition to this, an object which is referred by a live object is also considered as
reachable. These reachable objects are accessible by the executing program; hence, these
objects should remain on the heap as long as they are required. An object which is not
reachable can be garbage collected since there is no way a program can access it.
So the available System.gc() method can be used to request garbage collection. And the
System.runFinalization() method is used to run finalizers for all the eligible objects for GC.
Listing 1: The sample describes the syntax for calling garbage collection and finalizer
Listing 2: Sample program performs garbage collection. The free memory before and after
garbage collection is returned and displayed.
import java.util.*;
class GarbageCollectionDemo
{
public static void main(String s[]) throws Exception
{
// Get runtime environment
Runtime rt = Runtime.getRuntime();
System.out.println("Free memory before GarbageCollection =+rt.freeMemory());
Garbage
JVM Option Parameter Other Options
Collector Type
Incremental Low
XX:+UseTrainGC Not supported after JSE 1.4.2
Pause Collector