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()java.lang.ref.Cleaner
Underneath, registerPhantomReference
Before Cleaner there was Object.finalize()--finalization=disabled
| Mechanism | Since | When cleanup runs | Best for |
|---|---|---|---|
tryAutoCloseable | Java 7 | Immediately, at the end of the block | Every resource, always the first choice |
finalize() | Java 1.0, deprecated for removal in Java 18 | Some time after the object is found unreachable | Nothing in new code |
PhantomReferenceReferenceQueue | Java 1.2 | After collection, when your own code polls the queue | Libraries with their own cleanup thread |
Cleaner | Java 9 | After collection, on the Cleaner's thread | A safety net behind close() |
Arena | Java 22 | When the arena is closed, or by GC for automatic arenas | Native memory with explicit lifetimes |
The programs below ran on JDK 21. They call System.gc()
The normal path and the safety net
A NativeBufferAutoCloseable
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:
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.
callsclose() , which runs the action and unregisters it.cleanable.clean() - Calling
twice released handle 2 only once:close() runs the action at most once, whether it is triggered byclean() or by the collector. That makesclose idempotent for free.close - 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
having been called helps find the code that leaks.close() - The action is a
nested class holding only the handle number. It has no path back to thestatic , which is what lets the buffer become unreachable.NativeBuffer - Every
starts its own daemon thread, so a library should create one Cleaner, keep it in aCleaner.create() 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.static final - 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
(Java 9) in aReference.reachabilityFence(this) block.finally
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.
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:
released correct 3
after GC: only the correct object was cleaned; the failing action printed nothing
- The lambda in
usesLambdaCapture , so it capturesthis.handle . 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.this - The inner class
inRelease is notInnerClass , so every instance carries a hidden reference to the outer object. Same leak, harder to see.static - The action of
did run, but its exception vanished: theThrowing Javadoc says exceptions thrown by cleaning actions are ignored. Catch and log inside the action.Cleaner
Only Correct
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.
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:
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()
How the JDK uses it: direct buffers
A direct ByteBufferclose()
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:
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()thisfinalize
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):
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
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.finalize - An object resurrected itself: its
storedfinalize 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.this
To check whether a library still depends on finalization, run its tests with --finalization=disabledfinalize
Choosing a cleanup strategy
| Situation | Use |
|---|---|
| Any resource with a clear owner | AutoCloseable |
| A class wrapping native resources that callers might forget to close | close()Cleaner |
| Detecting leaks during development | Log in the Cleaner action when it runs without close() |
| Native memory with explicit lifetime | An Arena |
| Work that must happen at shutdown | A shutdown hook or explicit close() |
Existing finalize() | Replace with AutoCloseable--finalization=disabled |
See