Cleaner and cleaning up resources
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Memory is freed by the garbage collector, but files, sockets, database connections and native memory are not. Java's answer is to close them yourself with try-with-resources, and to keep Cleaner only as a safety net for the times someone forgets.
Why finalize() was a bad idea
finalize() is a method of Object that the JVM may call some time after an object becomes unreachable, before its memory is reused. It was meant for cleanup, and it was deprecated in Java 9 and marked for removal in Java 18 (JEP 421).
// Old style. Do not write new code like this.class ReportFile { @Override protected void finalize() { // maybe later, maybe never close(); }}Java 18 and later can even switch finalization off with java --finalization=disabled, to test whether your program depends on it.
The problems are built in. There is no guarantee when, or whether, it runs: if the GC never needs to collect the object, or the program ends first, the cleanup never happens. On HotSpot it runs on one shared "Finalizer" thread, so one slow finalize() delays all the others. An object with finalize() needs at least two GC cycles to be freed, exceptions thrown inside it are silently ignored, and the method can even "resurrect" the object by storing this somewhere. So a file closed only in finalize() can stay open for hours, and a server opening files faster than finalizers run out of file handles long before it runs out of memory.
Example 1 · finalize() may never run
class ReportFile { final String name;
ReportFile(String name) { this.name = name; System.out.println("Opened " + name); }
@Override @SuppressWarnings("deprecation") protected void finalize() { // deprecated since Java 9: do not copy this System.out.println("finalize(): closing " + name); }}
public class FinalizeNeverRunsDemo { public static void main(String[] args) { for (int i = 1; i <= 3; i++) { ReportFile f = new ReportFile("marks-" + i + ".csv"); // ... write the report, then forget to close it ... } System.out.println("Main finished"); }}Opened marks-1.csv Opened marks-2.csv Opened marks-3.csv Main finished
What this code does
- Three report files are opened and forgotten. The program is small, so the GC never needs to collect them, and none of the three
finalize()calls happens before the JVM exits. Had they been real files, they would never have been closed by this code. - In a bigger program a GC might run and call some of them, at an unknown time, on another thread. That uncertainty is exactly why
finalize()is deprecated (and why this example needs@SuppressWarningsto compile quietly).
java.lang.ref.Cleaner (Java 9 and later)
Cleaner is a Java 9 class that runs a cleaning action after an object becomes unreachable. It is a safety net for resources that were not closed, not a replacement for close().
A Cleaner runs a cleanup action after an object becomes phantom reachable, that is, after the GC has found it unreachable. You create one with Cleaner.create() (it starts one daemon thread) and call cleaner.register(obj, action), where action is a Runnable.
Example 2 · A Cleaner runs after the object becomes unreachable
import java.lang.ref.Cleaner;
class PrinterJob { private static final Cleaner CLEANER = Cleaner.create();
// The state the cleanup needs. A static nested class: it does NOT point to the PrinterJob. private static class State implements Runnable { private final String spoolFile;
State(String spoolFile) { this.spoolFile = spoolFile; }
@Override public void run() { System.out.println("Cleaner: deleting " + spoolFile); } }
final String name;
PrinterJob(String name) { this.name = name; CLEANER.register(this, new State(name + ".spool")); }}
public class CleanerDemo { public static void main(String[] args) throws InterruptedException { PrinterJob job = new PrinterJob("hall-ticket-S101"); System.out.println("Printing " + job.name);
job = null; // the job object is now unreachable System.gc(); Thread.sleep(200); // the cleaning action runs on the Cleaner's own thread System.out.println("Main finished"); }}Printing hall-ticket-S101 Cleaner: deleting hall-ticket-S101.spool Main finished
What this code does
Stateis a static nested class holding only the spool file name, so it does not keep thePrinterJobalive. Afterjob = nulland a GC, the job is phantom reachable and the Cleaner's thread runsState.run().- The
sleepgives that thread time to run beforemainprints. Without the explicitSystem.gc(), the cleanup would happen only whenever the GC next collected the job, or never in a short program.
The call returns a Cleaner.Cleanable whose clean() runs the action at once; the action runs at most once either way. The golden rule: the action must not refer to the object. If it does, the object is always reachable from the Cleaner, never becomes phantom reachable, and the action never runs. That is why the usual pattern keeps the cleanup data in a static nested class, which has no hidden link to the outer object. A Cleaner is better than finalize() (no resurrection, your own thread, explicit clean()), but it is still driven by the GC. It runs only if and when the object is collected, and there is no guarantee it runs before the program exits.
try-with-resources comes first
try-with-resources closes every resource declared in its brackets as soon as the block ends, normally or with an exception. Any class that implements AutoCloseable (one method, close()) can be used.
Example 3 · try-with-resources closes in reverse order, even on errors
class DbConnection implements AutoCloseable { final String name;
DbConnection(String name) { this.name = name; System.out.println("open " + name); }
void query(String sql) { if (sql.contains("DROP")) { throw new IllegalStateException("query refused: " + sql); } System.out.println("run " + sql + " on " + name); }
@Override public void close() { System.out.println("close " + name); }}
public class TryWithResourcesDemo { public static void main(String[] args) { try (DbConnection fees = new DbConnection("fees-db"); DbConnection hostel = new DbConnection("hostel-db")) { fees.query("SELECT due FROM fees"); hostel.query("SELECT room FROM rooms"); }
System.out.println("--- with an exception ---"); try (DbConnection fees = new DbConnection("fees-db")) { fees.query("DROP TABLE fees"); System.out.println("never printed"); } catch (IllegalStateException e) { System.out.println("caught: " + e.getMessage()); } }}open fees-db open hostel-db run SELECT due FROM fees on fees-db run SELECT room FROM rooms on hostel-db close hostel-db close fees-db --- with an exception --- open fees-db close fees-db caught: query refused: DROP TABLE fees
What this code does
- Both connections close as soon as the block ends,
hostel-dbfirst because it was opened last. No GC is involved: closing happens at a known line of code. - In the second block the query throws, yet
close fees-dbis printed before thecatchruns. try-with-resources closes the resource first, then hands the exception to thecatch.
Resources close in the reverse order of opening, so a statement closes before the connection it was made from. This is the real cleanup tool: the moment of closing is known, it does not depend on the GC, and it works the same on every JVM. If close() throws while another exception is already on its way out, the close exception is attached to it as a suppressed exception (e.getSuppressed()) instead of hiding it. Rule of thumb: if your class holds something outside the heap, implement AutoCloseable and make callers use try-with-resources. Everything else in this lesson is backup.
Order of execution
What try-with-resources does
Tap the steps in the order they happen.
A Cleaner as a safety net only
A safety net catches the mistake of a caller who forgot close(). The pattern combines both tools: register a Cleaner in the constructor, keep the returned Cleanable, and make close() call cleanable.clean().
Example 4 · Safety net: close() normally, Cleaner if forgotten
import java.lang.ref.Cleaner;
class OffHeapBuffer implements AutoCloseable { private static final Cleaner CLEANER = Cleaner.create();
private static class State implements Runnable { private final String id;
State(String id) { this.id = id; }
@Override public void run() { System.out.println(" freeing native memory of " + id); } }
private final Cleaner.Cleanable cleanable;
OffHeapBuffer(String id) { this.cleanable = CLEANER.register(this, new State(id)); }
@Override public void close() { cleanable.clean(); // runs the action now; it never runs a second time }}
public class SafetyNetDemo { public static void main(String[] args) throws InterruptedException { System.out.println("Closed properly:"); try (OffHeapBuffer b = new OffHeapBuffer("buffer-1")) { System.out.println(" using buffer-1"); }
System.out.println("Forgotten:"); OffHeapBuffer leaked = new OffHeapBuffer("buffer-2"); System.out.println(" using buffer-2, never closed"); leaked = null; System.gc(); Thread.sleep(200);
System.out.println("Main finished"); }}Closed properly: using buffer-1 freeing native memory of buffer-1 Forgotten: using buffer-2, never closed freeing native memory of buffer-2 Main finished
What this code does
buffer-1is closed by try-with-resources, which callscleanable.clean(): the native memory is freed right away and the Cleaner will not run the action again.buffer-2is never closed. Only when the GC finds it unreachable does the Cleaner free its memory. In a real program that could be minutes later, so the safety net limits the damage but does not replaceclose().
Example 5 · Bug: a cleaning action that captures this
import java.lang.ref.Cleaner;
class BuggyUpload { static final Cleaner CLEANER = Cleaner.create(); final String tempFile;
BuggyUpload(String tempFile) { this.tempFile = tempFile; // BUG: the lambda reads this.tempFile, so it captures 'this'. CLEANER.register(this, () -> System.out.println(" deleting " + this.tempFile)); }}
class FixedUpload { static final Cleaner CLEANER = Cleaner.create(); final String tempFile;
FixedUpload(String tempFile) { this.tempFile = tempFile; String file = tempFile; // copy what the action needs into a local CLEANER.register(this, () -> System.out.println(" deleting " + file)); }}
public class CleanerCaptureBugDemo { public static void main(String[] args) throws InterruptedException { new BuggyUpload("upload-1.tmp"); new FixedUpload("upload-2.tmp"); System.gc(); Thread.sleep(200); System.out.println("Main finished"); }}deleting upload-2.tmp Main finished
What this code does
- The
BuggyUploadlambda readsthis.tempFile, so the lambda holdsthis. The Cleaner holds the lambda, so the upload object stays reachable for ever: its action never runs, and every such object leaks. FixedUploadcopies the file name into a localfilefirst; its lambda captures only the string. After the GC onlyupload-2.tmpis deleted, which proves the difference.
A careful caller closes the resource at once with try-with-resources; a careless one still gets it released, later, when the GC collects the object. Because clean() runs the action at most once, calling close() twice, or closing and later being collected, never frees a resource twice. Some classes also log a warning inside the action when it ran without close(), so the missing close() gets fixed. The most common bug is a lambda action that reads a field, such as () -> delete(this.tempFile). Reading this.tempFile captures this, so the object can never be collected: the safety net turns into a memory leak. Copy what the action needs into a local variable, or use a static nested class.
Next step
Check your understanding
12 quick questions