简体   繁体   English

如何为建筑上开放的资源实施自动关闭

[英]How to implement Autocloseable for resource opened on construction

I am have a resource I open on construction of my object. 我有打开我的对象构造的资源。 I use it to write throughout the lifetime of the object. 我用它来写对象的整个生命周期。 But my application can close without warning and I need to capture this. 但是我的应用程序可以关闭而不会发出警告,我需要捕获这一点。 The class is pretty straightforward. 该类非常简单。

public class SomeWriter {
    private Metrics metrics;

    public SomeWriter() {
        try (metrics = new Metrics()) { // I know I can't but the idea is there
        }
    }

    public void write(String blah) {
       metrics.write(blah);
    }

    public void close() {
       metrics.close();
    }

So, you get the idea. 这样,您就知道了。 I'd like to "Autoclose" Metrics if the application goes down. 如果应用程序出现故障,我想“自动关闭”指标。

That is not possible with the try-with-resource concept, which is for local scope only. 使用资源试一试的概念是不可能的,仅适用于本地范围。 The way you close the Metrics within your close() is the best you can do. close()关闭Metrics的方法是最好的方法。

You best bet is to have SomeWriter also implement AutoCloseable and use the writer itself in the try-with-resources block, as in 最好的选择是让SomeWriter也实现AutoCloseable并在try-with-resources块中使用writer本身,例如

try (SomeWriter writer = new SomeWriter()) {
}
// here, the Metrics will also have been closed.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Hibernate“资源类型Session没有实现java.lang.AutoCloseable” - Hibernate “The resource type Session does not implement java.lang.AutoCloseable” 如何将ExecuteService与包含AutoCloseable资源的自定义线程一起使用 - How to use ExecuteService with custom Threads that contain a AutoCloseable resource Java try-catch 连接中的错误“资源类型连接未实现 java.lang.AutoCloseable” - Java error "The resource type Connection does not implement java.lang.AutoCloseable" in the try-catch connection 工厂创建的实例的AutoCloseable“资源泄漏”警告? - AutoCloseable “resource leak” warning for factory created instances? AutoCloseable contract:写入close()允许的资源? - AutoCloseable contract: writing to resource allowed in close()? 当AutoCloseable为null时,尝试使用资源 - Try-With Resource when AutoCloseable is null try-resource-block中的AutoCloseable延迟执行 - AutoCloseable Delayed Execution in try-resource-block 为什么ExecutorService接口没有实现AutoCloseable? - Why does the ExecutorService interface not implement AutoCloseable? 如何使用锁包装器进行自动关闭? - How to use lock wrapper for autocloseable? 对于未实现 AutoCloseable 的类,使用 lambda 是否是一种安全、正确且等效的解决方法? - Is using a lambda a safe, correct, and equivalent workaround for classes that do not implement AutoCloseable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM