Java 9 Cleaner 正确用法
2022-09-03 07:49:06
阅读有关Java 9的Cleaner类的信息,我在同一页面中发现了这个例子:
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();
}
}
在第二行中有一条评论说:
一个更干净的,最好是在库中共享的一个
为什么最好在库中共享一个(静态)?Cleaner
有没有人有一个很好的例子来说明如何使用而不是覆盖?Cleaner
finalize()