How to properly implement a finalizer for detecting resource leaks in Java

Let's say I created some resource class with the close () method to clear the resource, and I want to override finalize () to free the resource (and print a warning) if someone forgot to call close (), How can this be done correctly?

  • Is this recommended only for native resources (JNI-dedicated)?
  • What happens if you use the link to another object that was finalized from the finalizer? If there are circular dependencies, I don’t see how the garbage collector can prevent you from accessing objects whose finalizers could be executed.
  • Are there any better alternatives to overriding finalize () to detect and / or fix resource leaks?
  • Any other errors to consider when implementing the finalizer?

Note. I know that using finalize () is usually bad, and that it is not guaranteed to be called, there are several other issues discussing this. This question specifically addresses how to implement the finalizer in Java, and not about why you should (or shouldn't).

+5
source share
2 answers

java (2- ), № 7 , . , finalizer s. , , . , - , - , . - :

// Manual finalizer chaining
   @Override protected void finalize() throws Throwable {
       try {
           ... // Finalize subclass state
       } finally {
           super.finalize();
   } 
}

, - , finally - . , , . - --, . :

// Finalizer Guardian idiom
   public class Foo {
// Sole purpose of this object is to finalize outer Foo object
      private final Object finalizerGuardian = new Object() {
         @Override protected void finalize() throws Throwable {
            ... // Finalize outer Foo object
         }
      };
      ...  // Remainder omitted
}

, , .

- Closeable , . Josuha, finalize. JVM - . , - , .

+4

(JNI-)?

. . .

, Java, ?

, . , , - .

. , , , . , finalize() . finalize(), , . , null, , , .

finalize() / ?

, - / , . - , . , .

: , , , .

, ?

, , . , , . , , .

, .

: [ FileInputStream][1] [FileOutputStream][2], .

+1

All Articles