Saturday 2 March 2013

Garbage Collection in java


Objects are dynamically allocated by using the new operator such objects are destroyed automatically and their memory released for later reallocation in Java.  The technique that accomplishes this is called “Garbage Collection”.  Garbage collection works when no references to an object exist, the object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.  Java run-time implementations will take various approaches to garbage collection.

finalize( ) method:
            The garbage collector of an object called this method when the garbage collection determines that those are no more references to the object.  It is also placed some actions inside the finalized method.  The following points are related to finalize( ) method.
1.      Every class has Object class as a super class
2.      Every class in Java can have a finalize( ) method that returns resources to the system
3.      A class should have only one finalize( ) method that takes no argument.  Method finalize( ) is originally defined in class Object

            The finalize( ) method has the following syntax
            Syntax:            protected void finalize( )
                                    {
                                                      // finalization code
                                    }


Example:

class Garbage extends Object
{
            int x,y;
            void setdata(int a,int b)
            {
            x=a;
            y=b;
            }
            void printdata()
            {
            System.out.println("x="+x+"   y="+y);
            }
            protected void finalize()
            {
            System.out.println("finalizer");
            }
}
class Mg
{
            public static void main(String[] args)
            {
                        Garbage obj=new Garbage();
                        Garbage obj1=new Garbage();
                        obj.setdata(10,20);
                        obj.printdata();
                        obj1=null;
                        System.gc();          // method to call garbage collector
                        //obj1.setdata(2,3); //error
                        obj.printdata();
            }
}

O/P:    x=10    y=20
            finalizer
            x=10    y=20

No comments:

Post a Comment