gpt4 book ai didi

Java 9 Cleaner 正确用法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:21:58 35 4
gpt4 key购买 nike

阅读有关 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();
}
}

在第二行有一条评论说:

A cleaner, preferably one shared within a library

为什么在一个库中共享一个 Cleaner(静态)更好?

有没有人有关于如何使用 Cleaner 而不是覆盖 finalize() 的好例子?

最佳答案

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

清洁器有一个关联的线程。线程是有限的 native 资源。因此,我们的目标是通过不创建不必要的清洁器来限制创建的线程数量。

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

您发布了引用示例。如果这还不够,您需要提出更具体的问题。

关于Java 9 Cleaner 正确用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49510212/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com