Tuesday, 9 July 2019

finalize() method explained

finalize() method:

First point about finalize is that, IT IS DEPRECATED now.

Important points about finalize() method:
  • It is defined in java.lang.Object class.
  • It is called by GC thread [by JVM]. And it is not guaranteed whether it will be called or not even when an object becomes eligible for garbage collection and when it will be called.
  • If finalize() method throws any exception ,then the exception is ignored by GC and  finalize()  will never be called again for that object.
  • We must call finalize() of super class and that call must be in finally block. e.g.



    protected void finalize() throws Throwable {

        try{

            System.out.println("Finalize of Sub Class");

            //release resources, perform cleanup ;

        }catch(Throwable t){

            throw t;

        }finally{

            System.out.println("Calling finalize of Super Class");

            super.finalize();

        }

    }

Questions on finalize() method:

Question: Can we call finalize() method as normal method?
Answer: This method is called by GC thread before collecting object and is not intended to be called like normal method.

Question: Is there any guarantee that finalize() method gets surely called?
Answer: There is one way , you can guarantee running of finalize() method by calling System.runFinalization() and Runtime.getRuntime().runFinalization(). These methods ensures that JVM call finalize() method of all object which are eligible for garbage collection and whose finalize has not yet called.

Question: Does calling finalize() affects performance?
Answer: Yes. It is slow.

Question: Why finalize() method is protected in Object class?
Answer: 


  • If it was private, then subclasses couldn’t override it.
  • If it was public, then it could be called by anyone other than the JVM.
  • So, it is protected , so that it can be accessed by subclasses.
  • If it was default, then our own class must be in java.lang package.


Question: When an object is handling a FileConnection, then making that object reference null should release that connection as GC will take care of that. So, why we should override finalize() for releasing resources?

Answer: We should not override finalize() method at all. It is deprecated. We should release the FileConnection ourselves manually.
If we depend on GC for this, then GC may keep that reference around for long time and we may run out of resources like Handlers, Connections, Socket on O.S. level soon.




If this post really helpful, Please hit 'Like' on this page.


Thanks!

No comments:

Post a Comment