Cleaner Register Runs Cleanup

Register a cleanup action with java.lang.ref.Cleaner, call Cleanable.clean explicitly, and show that repeat calls stay idempotent.

JavaResilience

Code

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

public class Main {
    static final class Resource implements AutoCloseable {
        private final String name;
        private final Cleaner.Cleanable cleanable;

        Resource(String name, AtomicInteger cleanups, Cleaner cleaner) {
            this.name = name;
            // the cleanup action must not capture the resource itself
            this.cleanable = cleaner.register(this, () -> cleanups.incrementAndGet());
        }

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

        @Override
        public String toString() {
            return "Resource(" + name + ")";
        }
    }

    public static void main(String[] args) {
        Cleaner cleaner = Cleaner.create();
        AtomicInteger cleanups = new AtomicInteger();

        Resource first = new Resource("first", cleanups, cleaner);
        System.out.println("registered: " + first);
        first.close();
        System.out.println("after close: " + cleanups.get());

        // clean is idempotent, a second call does not run the action again
        first.close();
        System.out.println("after second close: " + cleanups.get());

        // try-with-resources routes through the same cleanable
        try (Resource second = new Resource("second", cleanups, cleaner)) {
            System.out.println("inside try: " + second);
        }
        System.out.println("after try: " + cleanups.get());
    }
}

How it works

The code’s whole job belongs to the classes Main and Resource and the functions close, toString and main.

Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

The primary signature is public void close()

Output lines are prefixed (registered:, after close:, after second close:), and the trail from step to printed line never breaks.

Running the file executes main, which drives close in order.

Key statements

return "Resource(" + name + ")";

Interactive Tools for This Topic

FAQ

What does Cleaner Register Runs Cleanup print when run?
Running the file directly is enough — expect labeled output lines such as `registered:`, `after close:`, `after second close:`.