title: Usage of java.lang.ref.Cleaner as alternative to Object.finalize
body: <p>I need to clean up resources allocated by a JNI call. It's easy to do it by overriding <code>Object.finalize()</code> method. Since this method is deprecated starting with Java 9, I'm trying to achieve the same thing using the new <code>java.lang.ref.Cleaner</code> class.</p>
  <p>Here is the code for calling <code>ToBeCleaned.cleanUp</code> method before the instance is garbage collected:</p>
  <pre><code>import java.lang.ref.Cleaner;
  import java.lang.ref.WeakReference;
  
  public class ToBeCleaned {
  
      private static Cleaner cleaner = Cleaner.create();
  
      public ToBeCleaned() {
          cleaner.register(this, new CleanRunnable(this));
      }
  
      void cleanUp () {
          // do cleanup
      }
  
  
      static class CleanRunnable implements Runnable {
          // It has to be weak reference, otherwise ToBeCleaned instance
          // would never be eligible for GC
          private WeakReference&lt;ToBeCleaned&gt; toBeCleanedWeakReference;
  
          CleanRunnable(ToBeCleaned  toBeCleaned) {
              this.toBeCleanedWeakReference = new WeakReference&lt;&gt;(toBeCleaned);
          }
  
          @Override
          public void run() {
              toBeCleanedWeakReference.get().cleanUp();
          }
      }
  }
  </code></pre>
  <p>My question: Is this the right approach?</p>