Why would you ever implement finalize()?

You could use it as a backstop for an object holding an external resource (socket, file, etc). Implement a close() method and document that it needs to be called.

Implement finalize() to do the close() processing if you detect it hasn’t been done. Maybe with something dumped to stderr to point out that you’re cleaning up after a buggy caller.

It provides extra safety in an exceptional/buggy situation. Not every caller is going to do the correct try {} finally {} stuff every time. Unfortunate, but true in most environments.

I agree that it’s rarely needed. And as commenters point out, it comes with GC overhead. Only use if you need that “belt and suspenders” safety in a long-running app.

I see that as of Java 9, Object.finalize() is deprecated! They point us to java.lang.ref.Cleaner and java.lang.ref.PhantomReference as alternatives.

Leave a Comment