3

当你想使用某个AutoClosable对象时,你应该使用try-with-resources。行。但是,如果我想编写返回的方法AutoClosable怎么办?在您从某个地方创建或接收 AutoCloseable 对象后,您应该在出现异常时关闭它,如下所示:

    public static AutoCloseable methodReturningAutocloseable() {
        AutoCloseable autoCloseable = ... // create some AutoClosable
        try {
            ... // some work
        }
        catch (Throwable exception) {
            autoCloseable.close();
            throw exception;
        }
        return autoCloseable;
    }

如果你不写try/catch块,你会泄漏资源,该 autoCloseable 对象持有,以防出现异常// some work。但这try/catch还不够,因为autoCloseable.close()也可以抛出异常(按设计)。因此,上面的代码转换为

    public static AutoCloseable methodReturningAutocloseable() {
        AutoCloseable autoCloseable = ... // create some autoclosable
        try {
            ... // some work
        }
        catch (Throwable exception) {
            try {
                autoCloseable.close();
            }
            catch (Throwable exceptionInClose) {
                exception.addSuppressed(exceptionInClose);
                throw exception;
            }
            throw exception;
        }
        return autoCloseable;
    }

这是很多样板。有没有更好的方法在java中做到这一点?

4

1 回答 1

2

有一些走近。

  • 使用Execute Around 成语。重新设计接口以简化客户端实施并消除问题。
  • 忽略问题。听起来很傻,但这通常是使用 I/O 流装饰器包装时发生的情况。
  • 包装在代理AutoCloseable中并将其放入您的 try-with-resource 中。
  • 写出等价的 try-with-resource 使用 try-catch 和 try-finally。(我不会——讨厌。)
  • 将修改后的 try-with-resource 编写为库功能。该代码将成为 Execute Around 的客户端。
  • 用 try-catch 和 try-finally 编写异常处理老派风格。

编辑:我想我会重新审视答案,添加一些示例代码来娱乐。

执行成语

简单且最佳的解决方案。不幸的是,Java 库并没有大量使用它(这AccessController.doPrivileged是一个很大的例外),并且约定也没有很好地建立。与以往一样,没有支持特性的 Java 已检查异常使事情变得棘手。我们不能使用java.util.function并且必须发明我们自己的功能接口。

// Like Consumer, but with an exception.
interface Use<R, EXC extends Exception> {
    void use(R resource) throws EXC;
}

public static void withThing(String name, Use<InputStream,IOException> use) throws IOException {
     try (InputStream in = new FileInputStream(name)) {
         use.use(in);
     }
}

很好很简单。无需担心客户端代码会弄乱资源处理,因为它不会这样做。好的。

修改后的 try-with-resource 作为库功能,AutoCloseable在 try-with-resource 中实现为代理

它会变得丑陋。我们需要将获取、释放和初始化作为 lambdas 传递。直接在此方法中创建资源会打开一个小窗口,其中意外异常会导致泄漏。

public static InputStream newThing(String name) throws IOException {
    return returnResource(
        () -> new FileInputStream(name),
        InputStream::close,
        in -> {
            int ignore = in.read(); // some work
        }
    );
}

的一般实现returnResource如下所示。一个 hack,因为 try-with-resource 不支持这种事情并且 Java 库不能很好地支持检查的异常。注意仅限于一个异常(您可以使用未经检查的异常来表示没有检查的异常)。

interface Acquire<R, EXC extends Exception> {
    R acquire() throws EXC;
}
// Effectively the same as Use, but different.
interface Release<R, EXC extends Exception> {
    void release(R resource) throws EXC;
}

public static <R, EXC extends Exception> R returnResource(
    Acquire<R, EXC> acquire, Release<R, EXC> release, Use<R, EXC> initialize
) throws EXC {
    try (var adapter = new AutoCloseable() { // anonymous classes still define type
        private R resource = acquire.acquire();
        R get() {
            return resource;
        }
        void success() {
            resource = null;;
        }
        public void close() throws EXC {
           if (resource != null) {
               release.release(resource);
           }
        }
    }) {
        R resource = adapter.get();
        initialize.use(resource);
        adapter.success();
        return resource;
    }
}

如果我们将构建资源的参数与构建资源的参数分开,这可能会更清晰。

public static InputStream newThing(String name) throws IOException {
    return returnResource(
        name,
        FileInputStream::new,
        InputStream::close,
        in -> {
            int ignore = in.read(); // some work
        }
    );
}

// Like Function, but with a more descriptive name for a functional interface.
interface AcquireFrom<T, R, EXC extends Exception> {
    R acquire(T t) throws EXC;
}

public static <T, R, EXC extends Exception> R returnResource(
    T t, AcquireFrom<T, R, EXC> acquire, Release<R, EXC> release, Use<R, EXC> initialize
 ) throws EXC {
     return returnResource(() -> acquire.acquire(t), release, initialize);
 }

总而言之,以下事情是痛苦的:

  • 转移资源所有权。保持本地化。
  • java.util.function不支持检查异常。
  • Java 库不支持 Execute Around。
  • AutoCloseable::close声明它抛出Exception而不是作为类型的类型参数。
  • 没有总和类型的已检查异常。
  • 一般的 Java 语言语法。
于 2019-04-01T12:50:55.077 回答