Search code examples
javagarbage-collectionresources

Java 9 Cleaner Correct Usage


Reading about Java 9's Cleaner class, I found this example in the same page:

public class CleaningExample implements AutoCloseable {
    // A cleaner, preferably one shared within a library
    private static final Cleaner cleaner = <cleaner>;

    static class State implements Runnable {

        State(...) {
            // initialize State needed for cleaning action
        }

        public void run() {
            // cleanup action accessing State, executed at most once
        }
    }

    private final State;
    private final Cleaner.Cleanable cleanable

    public CleaningExample() {
        this.state = new State(...);
        this.cleanable = cleaner.register(this, state);
    }

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

In the second line there is a comment saying:

A cleaner, preferably one shared within a library

Why is it preferable to have one shared Cleaner (static) within a library?

Does anybody have a good example about how to use Cleaner instead of overriding finalize()?


Solution

  • Why is it preferable to have one shared Cleaner (static) within a library?

    A cleaner has an associated thread. Threads are limited native resources. So the goal is to limit the amount of Threads created by not creating more cleaners than necessary.

    Does anybody have a good example about how to use Cleaner instead of overriding finalize()?

    You posted the reference example. You need to ask more specific questions if that is insufficient.