JAVA | Explain in detail garbage collection mechanism in java.

Java garbage collection is the process by which Java programs perform automatic memory management. Java programs compile to byte code that can be run on a Java Virtual Machine. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds the unused objects and deletes them to free up memory. Java garbage collection is an automatic process.  

In C/C++, programmer is responsible for both creation and destruction of objects. Usually programmer neglects destruction of useless objects. Due to this negligence, at certain point, for creation of new objects, sufficient memory may not be available and entire program will terminate abnormally causing OutOfMemoryErrors. 

But in Java, the programmer need not to care for all those objects which are no longer in use. Garbage collector destroys these objects. Main objective of Garbage Collector is to free heap memory by
destroying unreachableobjects. 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.

Syntax :
protected void finalize() throws Throwable
{
//code ;
}
Based on our requirement, we can override finalize() method for perform our cleanup activities like closing connection from database. 

Post a Comment

0 Comments