【问题标题】:How to implement Autocloseable for resource opened on construction如何为施工中打开的资源实现自动关闭
【发布时间】:2018-03-26 14:31:19
【问题描述】:

我在构建对象时打开了一个资源。我用它来编写对象的整个生命周期。但是我的应用程序可以在没有警告的情况下关闭,我需要捕获它。课程非常简单。

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();
    }

所以,你明白了。如果应用程序出现故障,我想“自动关闭”指标。

【问题讨论】:

    标签: java autocloseable


    【解决方案1】:

    try-with-resource 概念无法做到这一点,该概念仅适用于本地范围。在close() 中关闭Metrics 的方式是您能做的最好的事情。

    最好的办法是让 SomeWriter 也实现 AutoCloseable 并在 try-with-resources 块中使用编写器本身,如

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      相关资源
      最近更新 更多