Reputation: 761
I have an Iterator backed by a ResultSet. I need that for a row-level post-processing. The iterator implements AutoCloseable inteface. The connection remains open up until we iterate through all the rows / iteration interrupted by the user. And everything is fine if the consumer of the iterator calls close() method explicitly or is wrapping the use of the iterator in a Java7 try block. However, if the consumer doesn't do so I can't guarantee that the connection will be returned to the pool. In C# world we would do a finalizer and call Dispose(bool) from the finalizer as a fallback option. Should we do the same in Java?
Upvotes: 0
Views: 894
Reputation: 269687
This kind of cleanup generally isn't done in a Java finalize()
method. Failing to ensure proper disposal of a resource is a programming error; trying to clean up after bad programming is enabling the continuation of bad practices.
What is more common is a debugging option to help developers who've acknowledged they have a problem. Usually this isn't enabled by default, because of the overhead involved, but when the right flag is turned on, a stack trace is created when the resource is allocated. If finalize()
is invoked without the resource being destroyed properly, the stack is logged to show the location of the leak.
There are a number of caveats around finalize()
, and you should generally avoid it. One of the main problems in this case is that there's no guarantee it will ever be invoked, and even if it is, it may not be in time to help.
Upvotes: 3