When should we really use finalize() method in java?
If we want to close connection in finalize() method then it's better to use the code below as waiting for GC to call finalize() method and then release the connection does not make sense
try{
// Connection creation
}finally{
//close connection
}
So the question is does finalize() method has any relevance today?
It is indeed preferable to release resources by calling a method explicitly. Finalizers are not necessarily called promptly or even at all. And they add a performance penalty.
However, finalizers may still be used as a safety net to release resources, in case the client has forgotten to dispose explicitly.
From the topic "Avoid finalizers" in Joshua Bloch's "Effective Java," 2nd ed.:
[D]on't use finalizers except as a safety net or to terminate noncritical native resources. In those rare instances where you do use a finalizer, remember to invoke super.finalize. If you use a finalizer as a safety net, remember to log the invalid usage from the finalizer.
The only usecase I can think of for using finalize()
is:
Suppose you have a static resource (member) in your class and want to do some cleanup, finalization or logging on that resource at the time of class being unloaded then you need to override finalize()
method and do all that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With