# Understanding Garbage collection and finalize() method in - TopicsExpress



          

# Understanding Garbage collection and finalize() method in java: You all know that an object is created in the memory using new operator. Constructor is used to initialize the properties of that object. When an object is no more required, it must be removed from the memory so that that memory can be reused for other objects. Removing unwanted objects or abandoned objects from the memory is called garbage collection (GC). In the languages like C++, GC is performed manually using destructors. But, there is no destructors in java. In java, there exist better mechanism to handle the garbage collection. You need not to delete unwanted objects explicitly. JVM does this for you. JVM implicitly sweeps out abandoned objects from the memory. Before moving on to Garbage Collection in java, let’s have a look at the finalize() method of Object class. *finalize() method In Java: finalize() method is a protected and non-static method of java.lang.Object class. This method will be available in all objects you create in java. This method is used to perform some final operations or clean up operations on an object before it is removed from the memory. you can override the finalize() method to keep those operations you want to perform before an object is destroyed. Here is the general form of finalize() method. protected void finalize() throws Throwable { //Keep some resource closing operations here } Garbage Collection In Java : Whenever you run a java program, JVM creates three threads. 1) main thread 2) Thread Scheduler 3) Garbage Collector Thread. In these three threads, main thread is a user thread and remaining two are daemon threads which run in background. The task of main thread is to execute the main() method. The task of thread scheduler is to schedule the threads. The task of garbage collector thread is to sweep out abandoned objects from the heap memory. Abandoned objects or dead objects are those objects which does not have live references. Garbage collector thread before sweeping out an abandoned object, it calls finalize() method of that object. After finalize() method is 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. Garbage collector thread does not come to heap memory whenever an object becomes abandoned. It comes once in a while to the heap memory and at that time if it sees any abandoned objects, it sweeps out those objects after calling finalize() method on them. Garbage collector thread calls finalize() method only once for one object. continued......
Posted on: Sun, 31 Aug 2014 02:48:09 +0000

Trending Topics



Recently Viewed Topics




© 2015