4

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?

Jyotirup
  • 2,882
  • 9
  • 30
  • 38
  • 4
    `finally` and `finalize` are completely different things. – Paul Tomblin Dec 30 '11 at 17:17
  • 1
    And to answer your question, no, I have never implemented a finalize method in nearly 15 years of Java development. – Paul Tomblin Dec 30 '11 at 17:19
  • 1
    @PaulTomblin yup you are right what I'm trying to show here alternate to closing connection in finalize() method. It better I close the connection in finally block rather then wait for GC to call the finalize() then release my connection. Using finally{} I'm in control when the connection is getting released. Hope I'm making sense – Jyotirup Dec 30 '11 at 17:21
  • So my next part of the question is what is it's relevance in today's scenario – Jyotirup Dec 30 '11 at 17:22
  • possible duplicate of [Clean up code in finalize() or finally()?](http://stackoverflow.com/questions/1843905/clean-up-code-in-finalize-or-finally) – Perception Dec 30 '11 at 17:25

5 Answers5

7

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • 2
    Yep I usually put assertions in finalize (and configure the VM so that it runs the finalizers at shutdown) to make sure all resources were properly disposed of. Good to catch bugs while developing - but nothing that should ever be used in production. – Voo Dec 30 '11 at 17:32
2

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 4
    If you have a static resource, you certainly don't want to unload it every time an instance of the class is collected. If you need to release static resources (well all resources) at shutdown or some other time do it explicitly. That at least will work, contrary to using finalize. – Voo Dec 30 '11 at 17:54
  • What if your class is actually a `singleton` object, one that is loaded and unloaded only once (at the time of shutdown) in the lifetime of your application and you app happens to be just a POJO where you don't have any framework provided hooks for shutdown/destroy? – anubhava Dec 31 '11 at 05:12
  • I would agree with @Voo, even if a class is a singleton you would be better off to explicitly open() and close() the resource without relying on finalize() to be called. – eldjon Feb 23 '16 at 19:36
1

The short answer is never. Finalize() is full of subtle issues, and greatly slows garbage collections.

The longer answer is that maybe, maybe, during development, you want to check whether the important connection, file, socket or whatever was closed, and, if not, log a warning so that developers can investigate and properly fix the problem.

user949300
  • 15,364
  • 7
  • 35
  • 66
0

finalize()does not only release resource like socket, but also manage the memory. Theoretically speaking, you do not need to callfinalize() explicitly in your code. It is performed at proper time by the VM.

Summer_More_More_Tea
  • 12,740
  • 12
  • 51
  • 83
  • Under what circumstance should I override the finalize() method? – Jyotirup Dec 30 '11 at 17:24
  • @Jyotirup I never implement `finalize()` ever before. `finalize()` function is much like `destructor` in `C++` I think. And if you should override it, there must be something related to resource release. However, most of the time JVM will help you complete it correctly. A fast googling give me this http://www.google.com.hk/#hl=zh-CN&newwindow=1&safe=strict&sa=X&ei=2_T9ToWFCMqTiQeT1sntCg&ved=0CBkQvwUoAQ&q=when+to+override+finalize+java&spell=1&bav=on.2,or.r_gc.r_pw.,cf.osb&fp=a828595b5987e1c0&biw=1308&bih=596, I think the first three links may be helpful. – Summer_More_More_Tea Dec 30 '11 at 17:30
  • 3
    @Summer `finalize` is absolutely **NOT** similar to a destructor in c++. Destructors are deterministic - that's what makes them useful for RAII. Finalize has a couple of problems and most of all just isn't useful for anything other than finding bugs. Just don't use them - especially not if you don't understand what's happening under the hood (i.e. when does the JVM run finalizers and what are consequences of this) – Voo Dec 30 '11 at 17:51
-1

Practically finalize() shouldnt be used especially shouldnt be used to clean up resources. If a resource is acquired it is better from the performance perspective to explicitly release the resource rather than wait for JVM to call finalize(). You cannot foresee when JVM will call finalize() and if you are done with the resource you would be holding it unnecessarily for longer. I have seen somebody nullifying variables inside the finalize method, which is another bad practice as it slows down the program by extending GC cycles, with completely unnecessary lines of codes. GC is designed to handle very well dead objects clean up process.

eldjon
  • 2,800
  • 2
  • 20
  • 23