gpt4 book ai didi

java - try-with-resource 是否有可能无法关闭资源?

转载 作者:行者123 更新时间:2023-12-02 03:41:02 24 4
gpt4 key购买 nike

根据 Oracle 文档

The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource

如果资源未实现 AutoCloseable,则无法在 try block 中声明它,它必须在主体部分中声明,并且必须在 finally block 中显式关闭。try-with-resource 是否有可能无法清理资源,除非您错误地使用了习惯用法,例如存在嵌套资源并且 close() 调用对于底层资源不是幂等的?我的理解是 try-with-resource 仅确保 close() 在幕后被调用,但如果 close 本身不关闭底层资源,try-with-resource 将仍然对清理资源无效。有没有人有相反的观点或更多澄清?

最佳答案

是的。

try (FileSystem fs = FileSystems.getDefault()) {
return fs.getPath(aStringVar);
}

如果FileSystems.getDefault()返回一个sun.nio.fs.UnixFileSystem,就像我在使用Java 8 SE的RedHat机器上所做的那样,它会关闭时抛出UnsupportedOperationException。尽管 IntelliJ 显示警告并告诉您将其包装在 try-with-resources 中,但您不应该这样做,除非您想处理那个愚蠢的异常。

关于java - try-with-resource 是否有可能无法关闭资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36831233/

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