Wednesday, 20 August 2014

Garbage Collector In Java

Garbage Collector:

 In c,c++ programing language programmer show very much interest to allocate the memory but
it most of time it does not deallocate the memory due to this negligibility the chance of failing application is more

To overcome this problem:

 There is one component running in backround to destoy useless object due this componenet chances  of failing application is less due to memory promblem.

This component of JVM is nothing but Garbage Collector(GC)

hence main purpose of GC to destoy useless objects

The ways to make object Eligible for garbage collector:

Reassigning reference variable:

Student s=new Student();

Student s1=new Student();

//some line of code here

s=new Student();

//some line of code here


so s is eligible for garbage collector

Nullifing reference variable:

Student s=new Student();

//some line of code  here


so s is eligible for garbage collector

once we made object eligible for GC this object may not destroy by GC immediately
whevenever JVM run GC then these object will be destroy and we cannot except exctaly when
jvm run  GC it is JVM vendor dependent.

// this question asked in interview to one of my friend

Method for Requesting JVM to Run GC:

By using:


By Using:

Runtime r=Runtime.getRuntime();

this Runtime class has 3 method:

long freeMemory();
void gc();
long totalMemory();

out of this two 2nd one is best suitable because:
System.gc() is static method and r.gc() is instance method

static method are recommented to used over instance method because here
System.gc() internally called r.gc() method.

No comments:

Post a Comment