Let's say I have created some resource class with a close() method for cleaning up the resource, and I want to override finalize() to free the resource (and print a warning) if someone has forgotten to call close(). How can this be done properly?
- Is it recommended only for native (JNI-allocated) resources?
- What happens if you use a reference to another object that has been finalized, from a finalizer? If there are cyclic dependencies I don't see how the garbage collector can prevent you from accessing objects whose finalizers could have been executed.
- Are there any better alternatives to overriding finalize() for detecting and/or dealing with resource leaks?
- Any other pitfalls to be aware of when implementing a finalizer?
Note: I know that using finalize() is usually bad idea, and that it's not guaranteed to be called, there are several other questions discussing this. This question is specifically about how to implement a finalizer in Java, not about why you should (or shouldn't).