阅读
Java 9的
Cleaner类,我在同一页面中找到了这个例子:
public class CleaningExample implements AutoCloseable {
// A cleaner, preferably one shared within a library
private static final 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();
}
}
在第二行有评论说:
A cleaner, preferably one shared within a library
为什么在库中有一个共享清理程序(静态)更可取?
有没有人有一个关于如何使用Cleaner而不是覆盖finalize()的好例子?