Skip to main content
← PROBLEMS / LOW-LEVEL-DESIGN
An end-to-end domain learning journey

Replacing Finalizers with
AutoCloseable & Cleaner.

Objects overriding finalize() survive their initial GC cycle and pile up in a single-threaded Finalizer daemon queue; slow native cleanup lets allocation outpace finalization until the heap OOMs.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

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.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

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:

  1. 2+ GC Cycles per Object: Objects cannot be reclaimed in Young Gen; they survive into Old Gen waiting for the single Finalizer thread.
  2. Unbounded Queue Backlog: jmap -histo shows 12M Finalizer objects pinning 8 GB of heap and delaying native freeNative() calls until off-heap RAM also exhausts.
Finalizer Queue Bottleneck

Single-Threaded Finalizer Daemon vs. 20k/s Native Allocations

20k/s WorkersYoung/Old GC1x Finalizer Thread1. Alloc 20k/s JNI wrappers2. Promote to Old Gen + RefQueue3. Single thread drains <=10k/s4. 12M Finalizers -> 8GB Heap OOM!5. Fix: try-with-resources + Cleaner

AutoCloseable frees native memory deterministically on the caller thread, eliminating Finalizer promotion entirely.

Engineering Decision Framework
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); use AutoCloseable with try-with-resources for deterministic cleanup and java.lang.ref.Cleaner only 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.
Decision Exercise · Make the Call

When Replacing Finalizers with AutoCloseable & Cleaner experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

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 this in the cleanup lambda: CLEANER.register(this, () -> freeNative(this.handle)) holds a strong reference to this, so the object never becomes phantom-reachable and leaks forever.
  • Calling freeNative() directly in close(): Without cleanable.clean(), the Cleaner still fires later and triggers a C++ double-free segfault.
Component Topology

Why capturing `this` in Cleaner or skipping cleanable.clean() still leaks

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

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 via close() with zero GC delay.
  • static final class NativeState implements Runnable: Holds only the raw long handle and an AtomicBoolean freed—never a reference to the enclosing NativeImageBuffer.
  • Single-Shot cleanable.clean(): close() delegates to cleanable.clean(), which invokes NativeState.run() at most once and deregisters the Cleanable so double-free is impossible.
Idempotent Native Cleanup

Deterministic close() vs. Phantom-Reachable Cleaner Safety Net

try-with-resources close()caller forgot close()ALLOCATEDfreed=false, JNI activeTRY_CLOSEDcleanable.clean() -> CASGC_CLEANERFallback if close skippe

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
    }
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

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 ByteBuffer Pools: Pairs explicit release() reference counting with leak detection.
  • Java 22+ Foreign Function & Memory (Arena): Replaces JNI + Cleaner with deterministic confined/shared Arena scopes.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why MUST a `java.lang.ref.Cleaner` action be a `static` nested class (or non-capturing lambda) rather than an instance lambda referencing `this`?

Recommended Learning Flow