Video in progress
finalize() was deprecated. When designing a library that holds native resources, how do you organize cleanup?
The main mechanism is AutoCloseable and try-with-resources: the resource is closed at a known time. Cleaner is added only as a safety net, for cases where the user forgot close().
📖 Answer
finalize() was deprecated in JDK 9 and marked for removal in JDK 18 (JEP 421). It had many problems: the time it runs isn't guaranteed, if the finalizer thread is slow the objects pile up in a queue and fill the heap, an object can be "resurrected", and finalizable objects survive at least two GC cycles.
The right design:
public final class NativeBuffer implements AutoCloseable {
private static final Cleaner CLEANER = Cleaner.create();
private final State state;
private final Cleaner.Cleanable cleanable;
public NativeBuffer(long size) {
this.state = new State(Native.alloc(size));
this.cleanable = CLEANER.register(this, state);
}
@Override public void close() { cleanable.clean(); } // runs only once
// static: it must not hold a reference to the outer object
private record State(long address) implements Runnable {
public void run() { Native.free(address); }
}
}
The most common mistake here is leaving a reference to this in the cleaning action (for example, a lambda capturing the outer object). Then the object never becomes unreachable and the Cleaner never runs.
In library design also: make close() idempotent, make use of a closed resource throw a clear exception, and mark the cases where the Cleaner ran with a log or a metric, because that is a signal that "a user keeps forgetting close". To test with finalization turned off entirely, JDK 18+ has --finalization=disabled; you can use it to check whether old libraries depend on it.
Sign up to mark studied questions and save your progress.