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
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.
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
If you are looking for alternatives to finalize()
the proper question would be:
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.