I need to clean up resources allocated by a JNI call. It's easy to do it by overriding Object.finalize() method. Since this method is deprecated starting with Java 9, I'm trying to achieve the same thing using the new java.lang.ref.Cleaner class.
Here is the code for calling ToBeCleaned.cleanUp method before the instance is garbage collected:
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<ToBeCleaned> toBeCleanedWeakReference;
CleanRunnable(ToBeCleaned toBeCleaned) {
this.toBeCleanedWeakReference = new WeakReference<>(toBeCleaned);
}
@Override
public void run() {
toBeCleanedWeakReference.get().cleanUp();
}
}
}
My question: Is this the right approach?