Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Cleaner — explicit and fallback cleanup

Cleaner registers a cleanup action. Invoke it explicitly through Cleanable.clean(); automatic execution is a fallback mechanism.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Cleaner cleaner = Cleaner.create();
Cleaner.Cleanable cleanable = cleaner.register(owner, action);
cleanable.clean();

Cleaner in java.lang.ref manages cleanup actions. Cleaner.create() creates an instance with a daemon thread. Cleaner.register(owner, action) associates an object with a Runnable action and returns a Cleaner.Cleanable.

Cleaner.Cleanable.clean() unregisters the action and invokes it. The action runs at most once, regardless of the number of clean() calls. Prefer explicit closing, for example through AutoCloseable and try-with-resources.

Automatic cleanup follows notification that the object is phantom reachable; do not depend on its timing or execution during System.exit. The action must not retain its owner: use a static nested class rather than a lambda capturing this. Actions should be short, nonblocking, and prepared to run concurrently with other actions.

Examples

import java.lang.ref.Cleaner;

public class CleanerDemo implements AutoCloseable {
    private static final Cleaner CLEANER = Cleaner.create();

    private static final class State implements Runnable {
        @Override
        public void run() {
            System.out.println("Cleanup");
        }
    }

    private final Cleaner.Cleanable cleanable =
            CLEANER.register(this, new State());

    @Override
    public void close() {
        cleanable.clean();
    }

    public static void main(String[] args) {
        try (CleanerDemo demo = new CleanerDemo()) {
            System.out.println("Working");
            demo.close();
            demo.close();
        }
    }
}

Result

Working
Cleanup

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources