Garbage Collection

 

In java, garbage means unreferenced objects. 

Garbage Collection is a process of removing the unused memory automatically. In other words, it is a way to destroy the unused objects.

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.

 

In java object is created in the memory using new operator.

This facility makes java memory efficient because it removes unreferenced objects from heap memory , and it is automatic.

 

In java , it is the responsibility of the system and not of the programmer, to keep track of which objects are "Garbage".

 

As java uses garbage collection, errors like memory leak or dangling pointer are simply impossible.

How can an object be unreferenced?

There are many ways:

By nulling the reference

        Student s = new Student();

                      s= null ;

By assigning a reference to another

    Student s = new Student();

    Student s1= new Student();

        s=s1;

By anonymous object etc.

        new Student();

Unwanted objects or dead objects are those objects which are not live references. Garbage collector before removing out an unwanted object, it calls finalize() method of that object.

After finalize() method i  executed, object is destroyed from the memory. that means clean up operations which you have kept in the finalize() method are executed before an object is destroyed from the memory.


 

Finalization :-

    Just before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object.

This method is used to perform final operations or clean up operations on an object before it is removed from the memory.


general form  of finalize method is :-

     

        protected void finalize(){

                //code

                    }

Post a Comment

0 Comments