Advertisement

What is destructor in Java? How does destructor work

 What is destructor in Java?

Like constructor it is also a special method, which automatically get called when an object is no longer used. The destructor is the opposite of the constructor. The constructor is used to initialize objects while the destructor is used to delete or destroy the object that releases the resource occupied by the object. When the object completes its life cycle then garbage collector remove the memory used by that object. Destructor in Java is also called finalizer, that are non deterministic. In Java, object allocation & deallocation is handled by garbage collector. The invocation of finalizer is not guaranteed because it invoke implicitly. The following tasks get executed when a destructor is called.


    1. Releasing the release locks
    2. Closing all the database connections or files
    3. Releasing all the network resources
    4. Other Housekeeping tasks
    5. Recovering the heap space allocated during the lifetime of an object.

destructor in java example, destructor in c++, constructor and destructor in java, java finalize constructor, in java what is destructor, importance of destructor in c++, destructor in python


Advantage of destructor in Java?

  1. It automatically free the memory/resources occupied by the object,
  2. It execute at the end of program, no call is required.
  3. It cannot be overloaded and does not accept any type of parameters.

How does destructor work?

As we known when we creates an object it occupies some some space/memory. These object are used by threads. When these object are no longer in use then it becomes illegible for garbage collection. Garbage collector release that memory which is occupied by the object, and now available for new objects. When garbage collector destroy the object, JRE calls finalize() method to close the connection of that object.


Java finalize() Method?

It is very complicated for the programmer to forcefully execute garbage collector to destroy the object but java provide alternative method to do the same. Java provides finalize() method which do the same as destructor. It is not a destructor but it provide more security. We can call it by using the method finalize () or calling the method system.runFinalizerOnExit(true). The syntax for finalize() method is here below. You need to call finalize() method explicitly, if you want to override the method.


Protected void finalize Throws Throwable()
{
// resources to be closed
}



CLICK HERE to learn what is Constructor in Java



Post a Comment

0 Comments