Clean up code in finalize() or finally()?

前端 未结 9 1035
不知归路
不知归路 2020-12-19 04:16

I had the general view that clean up of resources is done in the finally block,
recently I found this particular code snippet in a class and it was overridi

相关标签:
9条回答
  • 2020-12-19 04:49

    Joshua Bloch makes a very clear recommendation in his book Effective Java (2nd Edition). Copied from chapter 2 Item 7: Avoid finalizers:

    Finalizers are unpredictable, often dangerous, and generally unnecessary. Their use can cause erratic behavior, poor performance, and portability problems. Finalizers have a few valid uses, which we’ll cover later in this item, but as a rule of thumb, you should avoid finalizers.

    Please read the reference to find out why.

    0 讨论(0)
  • 2020-12-19 04:51

    Finalize is probably a bad idea if your application causes lots of these objects to be created. This is because finalize will cause a bottleneck as the objects become eligible for garbage collection.

    There are times when finalize is the only solution; but use finally whenever you can

    0 讨论(0)
  • 2020-12-19 04:52

    If you are looking for alternatives to finalize() the proper question would be:

    • Why use an explicit close() method like, for example, all the stream and writer/reader classes in java.io.* and many others - when there is finalize()?

    The other answers make it clear that the disadvantage of finalize() is that you have no way to force it to run, and neither do any who might use your code.

    Of course, calling a close() methode (best done in a finally block or in a close() method itself) has to be documented by the author and then remembered to be called by the ones using the code. But there are lots of examples (not only java.io.*) where this is imposed and it works.

    BTW: close() is merely a convention.

    0 讨论(0)
提交回复
热议问题