Saturday, February 7, 2009

Garbage collection

  • In the old languages like c++ ,the programmer is responsible for the both creation and destroying the objects.
  • New keywords for object creation.,for object creation ,’delete’ keyword for object destruction.
  • Usually the programmer takes very much care,while creating the objects ,but neglecting while destroying the objects.
  • At certain point of time there will be no space for the creation of object as entire memory is occupied with unused objects .As a result the entire application may fail.
  • So, in the old languages applications most of the time they failed because of lack of efficient memory management .
  • In order to resolve the above problem, sun people has introduced powerful Character called GARBAGE COLLECTOR in JAVA.
  • In java programmer is responsible for creation of objects where as Garbage collector is responsible for destroying the objects. Hence , in java , memory problems we never face usually, as a result java language is considered as the Robust.
  • HPJ meter , J PROBE, Tivoli(IBM),purfy plus(IBM),one some of the tools to locate the memory leaks.
  • The negative side of Garbage collector is ,if something goes wrong regarding object destination the programmer in not in a position to debug.
Making an object eligible for GARBAGE Collection:
It’s a good programming practice to make an object is eligible for Garbage Collector when ever the object is no longer use.

Nullifying the reference variable:
We can make explicitly eligible for Garbage Collector by assigning all the reference variables of that objects.If the objects does not have any references that object is always eligible for Garbage Collector.
Example:
Student s1=new Student();
Student s1=new Student();
s1=null;
s2=null;
s1,s2 destructed by Garbage Collector.

Reassigning the reference variable:
Student s1=new Student();
Student s2=new Student();
s1=s2;
In this case only ,one object is eligible for Garbage Collector .

As a part of method execution:
Example 1:
class Sample
{
public static void main(String arg[])
{
m1()
System.out.println(“hai”);
}
public static void m1()
Student s1=new Student();
Student s2=new Student();
}
All the objects which are created as the part of method execution are by default eligible for garbage collection except that method return an object.

Example 2:
class Sample
{
public static void main(String arg[])
{
String s3=m1();
System.out.println(“hai”);
}
public static Student m1()
{
Student s1=new Student ();
return s1;
Student s2=new Student();
}
}
In the case of example 1 ,two objects s1,s2 are eligible for Garbage Collector,automatically where as in the case of example 2 ,the objects pointed earlier by s2 is eligible for Garbage Collector after m1 method execution over.

Island of Isolation:
class Test
{
Test i;
public static void main(String arg[])
{
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
t1.i=t2;
t2.i=t3;
t3.i=t1;
t1=null; (no objects is eligible for Garbage Collector)
t2=null ; (no objects is eligible for Garbage Collector)
t3=null; (All 3 objects is eligible for Garbage Collector)
}
}
If an object does not have any references that object is eligible for Garbage Collector.
Even through objects having some references still the object is eligible for Garbage Collector,If all the references are internal references.
t1=null;
t2=null;
t3=null;

Three ways for requesting JVM to run Garbage Collector:
We can request the JVM to run Garbage Collector by using following ways.

By using system class:
  • By using System class method or by using Runtime class method ,we can request jvm to run Garbage Collector.
  • But JVM may accept the request ,we can’t give any assurance for that .
  • System class contain a static method Garbage Collector for requesting jvm to run Garbage Collector.System.gc();

By using Runtime class:
  • Java application can communicate with the jvm by using the static Runtime class object.
  • We can get a Runtime object by using the static method getRuntime() available in the Runtime class.
i.e Runtime r=Runtime.getRuntime();
getRuntime method is a factory method .
we can get the available heap memory (512 kb is the default size of heap) by using freeMemory() method.
i.e int size=r.freeMemory();
return free memory in bytes.
We can find the total heap size of JVM by using the following method .
i.e int size=r.totalMemory();
By using the following method we can request Garbage Collector.
r.gc();
gc() is the run time method in Runtime class where as it is static method in System class.

Garbage Collector Demo :
import java.util.*;
class RuntimeDemo
{
public static void main(String art[])
{
Runtime r=new Runtime.getRuntime();
System.out.println(r.totalMemory()); // 2031616.
System.out.println(r.freeMemory()); //1908904
for(int i=0;i<1000;i++)
java.util.Date d=new java.util.Date();
d=null;
}
System.out.println(r.freeMemory()); // 1884208
r.gc();
System.out.println(r.freeMemory()); //1943840
}
}
Among there two approaches we can prefer System.gc() as it is static and doesn’t require to create any object.

Finalization():
  • when the jvm runs the Garbage collector and in which order Garbage collector identifies the objects eligible for Garbage collection ,in which order it will destroy the objects and which algorithm Garbage collector following for all these things we can’t give any assurance.Because Garbage collector implementation is totally Virtual machine dependent
  • But most of the cases Garbage collector follows mark and sweep algorithm.
  • Once Garbage collector identifies an object eligible for Garbage collector,calls finalize method on that object just before destroying.
  • The finalize() method contains clenup code object class contain finalize() method with the following signature.
protected void finalize()throws Trowable.

Q)The difference between final ,finally,finalize().Among finally and finalize() which one is always preferable.
  • When the Garbage collector will run and whether it can destroy our object or not ,we can’t give any assurance .Hence when compared with finalize(),finally block is always preferable for maintaining clean up code.
Special cases:
Case 1:
class Sample
{
public static void main(string att[])
{
String s=new String(“java”);
s=null;
System.gc();
System.out.println(“end of the main method”);
}
public void finalize()
{
System.out.println(“finalize called”);
}
}
The output is:
end of the main method

case 2:
Sample s1=new Sample();
s1=null;
This time output is end of main followed by finalize called.
In the first case ,String class Garbage collectorwas called and hence no statement of finalize() printed.
Case 3:
class Sample
{
public static void main(String arr[])
{
Sample s=new Sample();
s.finalize();
}
public void finalize()
{
System.out.println(“finalize called”);
System.out.println(10/0);
}
}
output is:
finalize called
arithmetic exception.
s.null;
System.gc();
Then output is only “finalize called”.
While executing finalize() if any exception raising we can catch that exception by using try –catch .If any exception is uncaught that exception is simply ignored by the JVM,but the remaining statements inside finalize() will not execute.
Example:
class Sample
{
public static void main(String arr[])
{
Sample s=new Sample();
// s=null; //System.gc()
s.finalize();
}
public void finalize()
{
try
{
System.out.println(“finalize called”);
System.out.println(10/0);
}
System.out.println(ArithmaticException e)
{
System.out.println(“exception caught”);
}
}

case 4:
  • Once an Object is eligible to Garbage collector,then Garbage collector called finalize method on that object .If after completing finalize() the Garbage collector simply destroys that object.
  • But some times while executing finalize() method ,the object may get the reference .At that time after completing finalize(), Garbage collector won’t destroy that object.
  • After some time ,If the same object is eligible for Garbage collector ,this time Garbage collector won’t call finalize(0 method.Just it simply destroys that Object.
  • i.e on any object finalize () method calls at most once.
  • That is Garbage collector won’t call finalize method on any object then one time.
  • Once an object is eligible for Garbage collector it may not always eligible for Garbage collector until destroying of that object .In the middle it may get reference.
Example:
class FinalizeDemo
{
static FinalizeDemo f;
public static void main(String args[])throws Exception
{
FinalizeDemo d=FinalizeDemo();
System.out.println(d.hashcode()); //100
d=null;
System.gc(); //finalize called
Thread.sleep(2000);
System.out.println(f.hashCode()); //100
f=null;
System.gc();
Thread.sleep(400);
}
public void finalize()
{
System.out.println(“finalize called”);
f=this;
}
}

0 comments:

Post a Comment