Monday, 30 January 2012

Garbage Collection

•Objects are allocated memory dynamically using the “new” keyword.
•When the objects lifetime is completed, what happens to the memory allocated to the objects?
•In Java, memory management is taken care automatically. The programmer has no need to worry about the memory management.
•The technique which is used by Java to deallocate the dynamically allocated memory is “Garbage Collection”.

•When an object gets derefferenced or it is no longer accessed in the program, the JVM considers to garbage collect it.
•When an object gets garbage collected, depends on the JVM itself.

Finalization:
•Sometimes the objects might refer some external resources like files and databases.
•The connections opened to such resources must be explicitly closed for safety reasons.
•To perform such operations, Java provides a concept called “finalization”.
•For implementing this concept, Java provides a special method called “finalize()”, which is available in the “Object” class.
•JVM calls the “finalize()” method when it is about to recycle the memory of an object.

•Inside the finalize() method the code that is needed to close the connections or any other code must be written.
•The syntax of “finalize()” method is:
protected void finalize()
{
   statement(s);
}

No comments:

Post a Comment