When traffic spikes expose hidden coupling, never override `finalize()` (deprecated for removal); use `AutoCloseable` with `try-with-resources` for deterministic cleanup and `java.lang.ref.Cleaner` only as a non-capturing safety net.
TL;DR30-second simplified summary▾
Core Mechanics: Overriding Object.finalize() forces the JVM to wrap every NativeImageBuffer in a java.lang.ref.Finalizer, promote unreachable instances to Old Gen, and enqueue them onto a single-threaded Finalizer daemon.
Visual & Structural Flow: Depicts Single-Threaded Finalizer Daemon vs. 20k/s Native Allocations (20k/s Workers -> Young/Old GC -> 1x Finalizer Thread); Deterministic close() vs. Phantom-Reachable Cleaner Safety Net (ALLOCATED -> TRY_CLOSED -> GC_CLEANER).
Trade-Offs & Production: Two subtle bugs break naive Cleaner migrations: Capturing this in the cleanup lambda: CLEANER.register(this, () -> freeNative(this.handle)) holds a strong reference to. Replace finalize() (deprecated for removal) with deterministic AutoCloseable + an idempotent Cleaner safety net: Deterministic try-with-resources: Callers release.
Failure Modes & Application: Eliminating finalize() is mandatory in high-throughput JVM media, ML, and networking services: JNI Image/Video & Tensor Buffers: Prevents native RSS leaks in OpenCV, FFmpeg, and ONNX/PyTorch wrappers.
Why Java finalize() causes Old-Gen OOMs at 20,000 allocations/sec.
Why this matters: The mechanism: understand how Why Java finalize() causes Old-Gen OOMs at 20,000 allocations/sec works from first principles.
Think of Why Java finalize() causes Old-Gen OOMs at 20,000 allocations/sec as the intuition layer for Replacing Finalizers with AutoCloseable & Cleaner: The mechanism: understand how Why Java finalize() causes Old-Gen OOMs at 20,000 allocations/sec works from first principles.
Overriding Object.finalize() forces the JVM to wrap every NativeImageBuffer in a java.lang.ref.Finalizer, promote unreachable instances to Old Gen, and enqueue them onto a single-threaded Finalizer daemon. At 20,000 JNI allocations/sec, even 0.1 ms per native free caps throughput at 10,000/sec—causing 12M Finalizer instances to pile up until the 8 GB heap OOMs.
Two-cycle GC promotion, Finalizer queue backlog, and native leaks.
Why this matters: The problem: see what breaks without Two-cycle GC promotion, Finalizer queue backlog, and native leaks under real concurrency or scale.
Using finalize() degrades both JVM heap and off-heap native memory:
- 2+ GC Cycles per Object: Objects cannot be reclaimed in Young Gen; they survive into Old Gen waiting for the single
Finalizerthread. - Unbounded Queue Backlog:
jmap -histoshows12MFinalizerobjects pinning8 GBof heap and delaying nativefreeNative()calls until off-heap RAM also exhausts.
Single-Threaded Finalizer Daemon vs. 20k/s Native Allocations
AutoCloseable frees native memory deterministically on the caller thread, eliminating Finalizer promotion entirely.
- Problem
- How to implement Replacing Finalizers with AutoCloseable & Cleaner without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- When traffic spikes expose hidden coupling, never override
finalize()(deprecated for removal); useAutoCloseablewithtry-with-resourcesfor deterministic cleanup andjava.lang.ref.Cleaneronly as a non-capturing safety net. - Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Replacing Finalizers with AutoCloseable & Cleaner experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Why capturing `this` in Cleaner or skipping cleanable.clean() still leaks.
Why this matters: The problem: see what breaks without Why capturing this in Cleaner or skipping cleanable.clean under real concurrency or scale.
Two subtle bugs break naive Cleaner migrations:
- Capturing
thisin the cleanup lambda:CLEANER.register(this, () -> freeNative(this.handle))holds a strong reference tothis, so the object never becomes phantom-reachable and leaks forever. - Calling
freeNative()directly inclose(): Withoutcleanable.clean(), theCleanerstill fires later and triggers a C++ double-free segfault.
Why capturing `this` in Cleaner or skipping cleanable.clean() still leaks
Enterprise solution: AutoCloseable + Static Non-Capturing Cleaner State.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Replace finalize() (deprecated for removal) with deterministic AutoCloseable + an idempotent Cleaner safety net:
- Deterministic
try-with-resources: Callers release native buffers immediately viaclose()with zero GC delay. static final class NativeState implements Runnable: Holds only the rawlong handleand anAtomicBoolean freed—never a reference to the enclosingNativeImageBuffer.- Single-Shot
cleanable.clean():close()delegates tocleanable.clean(), which invokesNativeState.run()at most once and deregisters theCleanableso double-free is impossible.
Deterministic close() vs. Phantom-Reachable Cleaner Safety Net
AtomicBoolean + cleanable.clean() guarantee idempotent single-free across explicit close() and GC Cleaner.
public final class NativeImageBuffer implements AutoCloseable {
private static final Cleaner CLEANER = Cleaner.create();
private static final class NativeState implements Runnable {
private final long handle;
private final AtomicBoolean freed = new AtomicBoolean(false);
NativeState(long handle) { this.handle = handle; }
@Override public void run() {
if (freed.compareAndSet(false, true)) {
freeNative(handle);
}
}
}
private final NativeState state;
private final Cleaner.Cleanable cleanable;
public NativeImageBuffer(long handle) {
this.state = new NativeState(handle);
this.cleanable = CLEANER.register(this, this.state);
}
@Override public void close() {
cleanable.clean(); // Idempotent: invokes NativeState.run() once
}
}
Where deterministic off-heap lifecycle management is critical.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Eliminating finalize() is mandatory in high-throughput JVM media, ML, and networking services:
- JNI Image/Video & Tensor Buffers: Prevents native RSS leaks in OpenCV, FFmpeg, and ONNX/PyTorch wrappers.
- Netty / Direct
ByteBufferPools: Pairs explicitrelease()reference counting with leak detection. - Java 22+ Foreign Function & Memory (
Arena): Replaces JNI +Cleanerwith deterministic confined/sharedArenascopes.
Practice: Make the trade-off yourself.
Why MUST a `java.lang.ref.Cleaner` action be a `static` nested class (or non-capturing lambda) rather than an instance lambda referencing `this`?