Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should be we use finalize() method in java?

Tags:

java

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?

like image 697
Jyotirup Avatar asked Jan 17 '23 22:01

Jyotirup


2 Answers

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.

like image 132
Andy Thomas Avatar answered Jan 31 '23 22:01

Andy Thomas


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.

like image 34
anubhava Avatar answered Feb 01 '23 00:02

anubhava