The Cleaner API

Cleaner (Java 9) runs a cleanup action after an object becomes unreachable. It replaces finalize(), which is deprecated for removal, and is meant as a safety net for resources outside the Java heap when callers forget to close them. This page explains how a Cleaner works, shows the normal and safety-net paths, the three mistakes that silently disable it, why it gives no guarantee at exit, how the JDK uses it for direct buffers, and how it compares with finalize().

Contents

What a Cleaner does

Some objects own resources that the garbage collector knows nothing about: a native memory block, a file descriptor, a handle from a C library. The rule for those is explicit release, usually close() in try-with-resources. A java.lang.ref.Cleaner (Java 9) adds a safety net for callers who forget: you register an object together with a cleanup action, and when the garbage collector finds the object unreachable, the Cleaner runs the action on its own thread.

Underneath, register creates a PhantomReference to the object, linked to a reference queue. A phantom reference never gives access to its object, so nothing can bring the object back. When the collector decides the object is unreachable, it puts the reference on the queue, and the Cleaner's daemon thread takes it off and runs the action. Two rules follow: the action must not hold a reference to the object, or it never becomes unreachable; and the action runs at some point after a garbage collection, which may be much later or never.

Before Cleaner there was Object.finalize(), which the JVM called on the object itself before reclaiming it. It was deprecated in Java 9 and deprecated for removal in Java 18 (JEP 421), which also added --finalization=disabled to test applications without it.

Ways to release resources
MechanismSinceWhen cleanup runsBest for
try-with-resources and AutoCloseableJava 7Immediately, at the end of the blockEvery resource, always the first choice
finalize()Java 1.0, deprecated for removal in Java 18Some time after the object is found unreachableNothing in new code
PhantomReference with a ReferenceQueueJava 1.2After collection, when your own code polls the queueLibraries with their own cleanup thread
CleanerJava 9After collection, on the Cleaner's threadA safety net behind close()
Arena (Foreign Memory API)Java 22When the arena is closed, or by GC for automatic arenasNative memory with explicit lifetimes

The programs below ran on JDK 21. They call System.gc() several times to make collection happen during the demo; that call is only a request, which is why real code must never depend on it.

The normal path and the safety net

A NativeBuffer stands in for an object that owns a native handle. It registers a cleanup action and implements AutoCloseable by running that same action. The program uses it correctly, closes it twice, and finally forgets to close it.

Java
import java.lang.ref.Cleaner;

public class CleanerDemo {

    private static final Cleaner CLEANER = Cleaner.create();

    // The resource handle owns something outside the Java heap (simulated by an id)
    static final class NativeBuffer implements AutoCloseable {

        // The cleanup action must NOT reference the NativeBuffer itself,
        // or the buffer could never become unreachable. A static nested class is safe.
        private static final class Release implements Runnable {
            private final int handle;

            Release(int handle) {
                this.handle = handle;
            }

            @Override
            public void run() {
                System.out.println("  released native handle " + handle);
            }
        }

        private final Cleaner.Cleanable cleanable;

        NativeBuffer(int handle) {
            System.out.println("  allocated native handle " + handle);
            this.cleanable = CLEANER.register(this, new Release(handle));
        }

        String describe() {
            return "buffer in use";
        }

        @Override
        public void close() {
            cleanable.clean();                    // runs the action at most once
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("1. closed explicitly with try-with-resources:");
        try (NativeBuffer b = new NativeBuffer(1)) {
            System.out.println("  " + b.describe());
        }

        System.out.println("2. closed twice: the action runs only once");
        NativeBuffer twice = new NativeBuffer(2);
        twice.close();
        twice.close();

        System.out.println("3. forgotten: the Cleaner runs after garbage collection");
        new NativeBuffer(3);                     // never closed, immediately unreachable
        collectGarbage();

        System.out.println("done");
    }

    static void collectGarbage() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            System.gc();                         // a hint only; repeated to make the demo reliable
            Thread.sleep(50);
        }
    }
}

Output:

Output
1. closed explicitly with try-with-resources:
  allocated native handle 1
  buffer in use
  released native handle 1
2. closed twice: the action runs only once
  allocated native handle 2
  released native handle 2
3. forgotten: the Cleaner runs after garbage collection
  allocated native handle 3
  released native handle 3
done
  • With try-with-resources, handle 1 was released at the end of the block, deterministically. close() calls cleanable.clean(), which runs the action and unregisters it.
  • Calling close() twice released handle 2 only once: clean() runs the action at most once, whether it is triggered by close or by the collector. That makes close idempotent for free.
  • Handle 3 was never closed. After garbage collection, the Cleaner ran the action and released it anyway. That is the safety net, and it is also a bug report: logging in the action when it runs without close() having been called helps find the code that leaks.
  • The action is a static nested class holding only the handle number. It has no path back to the NativeBuffer, which is what lets the buffer become unreachable.
  • Every Cleaner.create() starts its own daemon thread, so a library should create one Cleaner, keep it in a static final field as here, and share it among all its objects. Actions run one at a time on that thread, so they must be short and must not block; a slow action delays every other cleanup in the library.
  • The object stays reachable while any method on it is still running, but the JIT may decide it is unreachable earlier than the source suggests, for example during the last call that uses only a copied handle. Code that passes the native handle to a native call should keep the object alive until the call returns with Reference.reachabilityFence(this) (Java 9) in a finally block.

Three mistakes that disable or hide cleanup

Four objects are registered in four ways, then garbage collection runs. Only one of them is written correctly.

Java
import java.lang.ref.Cleaner;

public class CleanerMistakes {

    private static final Cleaner CLEANER = Cleaner.create();

    // Mistake 1: a lambda that uses a field captures 'this'
    static final class LambdaCapture {
        private final int handle;

        LambdaCapture(int handle) {
            this.handle = handle;
            CLEANER.register(this, () -> System.out.println("  released " + this.handle));
        }
    }

    // Mistake 2: a non-static inner class holds a hidden reference to its outer object
    static final class InnerClass {
        private final int handle;

        InnerClass(int handle) {
            this.handle = handle;
            CLEANER.register(this, new Release());
        }

        class Release implements Runnable {                 // not static!
            @Override
            public void run() {
                System.out.println("  released " + handle);
            }
        }
    }

    // Correct: copy what the action needs into a local, capture only that
    static final class Correct {
        Correct(int handle) {
            int h = handle;                                  // no reference to 'this'
            CLEANER.register(this, () -> System.out.println("  released correct " + h));
        }
    }

    // Mistake 3: an exception in the action is swallowed silently
    static final class Throwing {
        Throwing() {
            CLEANER.register(this, () -> {
                throw new IllegalStateException("cleanup failed");
            });
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new LambdaCapture(1);
        new InnerClass(2);
        new Correct(3);
        new Throwing();
        for (int i = 0; i < 10; i++) {
            System.gc();
            Thread.sleep(50);
        }
        System.out.println("after GC: only the correct object was cleaned;"
                + " the failing action printed nothing");
    }
}

Output:

Output
released correct 3
after GC: only the correct object was cleaned; the failing action printed nothing
  1. The lambda in LambdaCapture uses this.handle, so it captures this. The Cleaner holds the action strongly, the action holds the object, and the object can never become unreachable: it is never cleaned and never freed. Nothing warns about this.
  2. The inner class Release in InnerClass is not static, so every instance carries a hidden reference to the outer object. Same leak, harder to see.
  3. The action of Throwing did run, but its exception vanished: the Cleaner Javadoc says exceptions thrown by cleaning actions are ignored. Catch and log inside the action.

Only Correct, which copied the handle into a local variable before creating the lambda, was released. A static nested class with explicit fields, as in the first program, makes the same guarantee easier to check in code review.

No guarantee at exit

A Cleaner action runs only after the collector has found the object unreachable. If the program ends before a collection happens, nothing runs. This program drops its only reference and ends without triggering a collection.

Java
import java.lang.ref.Cleaner;

public class NotAtExit {

    private static final Cleaner CLEANER = Cleaner.create();

    public static void main(String[] args) {
        Object resource = new Object();
        CLEANER.register(resource, () -> System.out.println("cleanup ran"));
        resource = null;                       // unreachable now, but no GC happens
        System.out.println("resource dropped; main ends without System.gc()");
        // The Cleaner thread is a daemon: at exit, pending actions are simply abandoned
    }
}

Output:

Output
resource dropped; main ends without System.gc()

"cleanup ran" never appeared. The Cleaner's thread is a daemon thread, and the JVM does not wait for pending actions at exit. A program with plenty of heap may never collect garbage at all during its lifetime. So a Cleaner must never be the sole mechanism that releases a resource, and anything that must happen at shutdown, such as flushing a file, belongs in a close() call or a shutdown hook. The operating system reclaims process resources like memory and file descriptors at exit anyway; resources outside the process, such as a lock file or a row in a database, are not reclaimed.

How the JDK uses it: direct buffers

A direct ByteBuffer owns native memory, and it has no close() method: the JDK frees the memory with an internal cleaner when the buffer object is collected. The program allocates 100 MB of direct buffers, drops them, and watches the JVM's "direct" buffer pool through its management bean.

Java
import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class DirectMemory {

    static long directMb() {
        for (BufferPoolMXBean pool : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) {
            if (pool.getName().equals("direct")) {
                return pool.getMemoryUsed() >> 20;
            }
        }
        return -1;
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("direct memory at start:      " + directMb() + " MB");
        List<ByteBuffer> buffers = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            buffers.add(ByteBuffer.allocateDirect(1 << 20));     // 1 MB of native memory
        }
        System.out.println("after 100 x allocateDirect:  " + directMb() + " MB");
        buffers.clear();                                         // unreachable, not yet freed
        System.out.println("references dropped, no GC:   " + directMb() + " MB");
        for (int i = 0; i < 10 && directMb() > 0; i++) {
            System.gc();                                          // the JDK's own Cleaner frees it
            Thread.sleep(50);
        }
        System.out.println("after GC ran the cleaners:   " + directMb() + " MB");
    }
}

Output:

Output
direct memory at start:      0 MB
after 100 x allocateDirect:  100 MB
references dropped, no GC:   100 MB
after GC ran the cleaners:   0 MB
  • After the references were dropped, the 100 MB were still in use: unreachable buffers hold their native memory until a collection finds them.
  • After garbage collection, the cleaners ran and direct memory went back to 0 MB.
  • This is why heavy direct buffer allocation can fail with "Cannot reserve ... bytes of direct buffer memory" while the heap looks almost empty: small buffer objects on the heap do not create enough pressure to trigger a collection. The JDK's allocator does try a collection before giving up, but the robust fix is to reuse direct buffers, as the ByteBuffer page recommends.

Cleaner versus finalize

The same 200,000 objects are allocated plain, registered with a Cleaner, and with a finalize() method that also stores this in a static field, something only finalize can do. Best of 3, a rough comparison.

Java
import java.lang.ref.Cleaner;
import java.util.concurrent.atomic.AtomicInteger;

public class FinalizeVsCleaner {

    static final AtomicInteger FINALIZED = new AtomicInteger();
    static final AtomicInteger CLEANED = new AtomicInteger();
    static final Cleaner CLEANER = Cleaner.create();
    static Object resurrected;

    static class WithFinalize {
        @Override
        @SuppressWarnings({"removal", "deprecation"})
        protected void finalize() {
            FINALIZED.incrementAndGet();
            resurrected = this;                    // finalize can bring the object back to life
        }
    }

    static class WithCleaner {
        WithCleaner() {
            CLEANER.register(this, CLEANED::incrementAndGet);
        }
    }

    static class Plain {
    }

    interface Factory {
        Object make();
    }

    static long allocate(Factory f, int n) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            for (int i = 0; i < n; i++) {
                f.make();
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best / 1000000;
    }

    public static void main(String[] args) throws InterruptedException {
        int n = 200000;
        System.out.printf("allocate %,d objects (best of 3, rough):%n", n);
        System.out.printf("  plain           %,5d ms%n", allocate(Plain::new, n));
        System.out.printf("  with Cleaner    %,5d ms%n", allocate(WithCleaner::new, n));
        System.out.printf("  with finalize() %,5d ms%n", allocate(WithFinalize::new, n));
        for (int i = 0; i < 20; i++) {
            System.gc();
            Thread.sleep(50);
        }
        System.out.println("after GC: some finalized " + (FINALIZED.get() > 0)
                + ", some cleaned " + (CLEANED.get() > 0));
        System.out.println("an object resurrected itself from finalize(): "
                + (resurrected != null));
    }
}

Output (2-CPU Linux machine, JDK 21, rough timing):

Output
allocate 200,000 objects (best of 3, rough):
  plain               0 ms
  with Cleaner       48 ms
  with finalize()    18 ms
after GC: some finalized true, some cleaned true
an object resurrected itself from finalize(): true
  • Both mechanisms made allocation far more expensive than plain objects, which cost almost nothing to allocate: a finalizable object must be registered with the JVM when created, and a Cleaner registration creates a phantom reference and links it into a list. Neither belongs on objects created in large numbers.
  • The costs do not end there. A finalizable object survives at least one extra collection, because finalize must run before the memory can be reclaimed, and all finalizers share one thread, so a slow finalizer delays all the others. Cleaner actions also share a thread per Cleaner, but you can create several Cleaners.
  • An object resurrected itself: its finalize stored this in a static field, and the object was reachable again after being declared dead. Such objects are never finalized a second time. Phantom references make that impossible, which is one of the main reasons Cleaner replaced finalization.

To check whether a library still depends on finalization, run its tests with --finalization=disabled (Java 18): finalize methods are then never called.

Choosing a cleanup strategy

Releasing resources correctly
SituationUse
Any resource with a clear ownerAutoCloseable and try-with-resources
A class wrapping native resources that callers might forget to closeclose() plus a Cleaner registered in the constructor, with a static action
Detecting leaks during developmentLog in the Cleaner action when it runs without close()
Native memory with explicit lifetimeAn Arena; see foreign memory
Work that must happen at shutdownA shutdown hook or explicit close(), never a Cleaner
Existing finalize() methodsReplace with AutoCloseable plus Cleaner; test with --finalization=disabled

See reference types for phantom, weak and soft references, try-with-resources for the explicit path, and garbage collection for when collections actually happen.