英文:
Who closes an `InputStream` that is Returned from within a try with resources block?
问题
在进行代码审查时,我遇到了一些看起来像这样的代码:
try (InputStream stream = new BufferedInputStream(resource)) {
return stream;
}
其中resource
在方法的其他地方被定义。请注意,这只是示例代码,在实际情况中,重要的是要关闭stream
,以免资源泄漏。
我的问题是:try-with-resources代码块会自动关闭stream
吗?一旦stream
被返回给调用者,他们可能会尝试对其进行一些有用的操作,或者更糟的是,将其保存在从未被清理的全局变量中。
try-with-resources代码块会追踪这个引用并可靠地清理它吗?在我阅读的所有关于这种语法的教程或文档中,我都找不到答案。
我的直觉告诉我,更好的做法是将流的内容复制到其他对象中,然后返回该对象以确保流被关闭。
英文:
When doing a code review, I stumbled on some code that looks like this:
try (InputStream stream = new BufferedInputStream(resource)) {
return stream;
}
where resource
was defined elsewhere in the method. Note that this is sample code and that in real life, it's important that stream
is closed so as not to leak resources.
My question is this: Will the try with resources block close stream
on my behalf? Once stream
has been returned to the caller, they might try to do something useful with it, or god forbid, hold a reference to it in a global variable that never gets cleaned up.
Will the try with resources block follow this reference around and dutifully clean it up? I can't find an answer to this in any of the tutorials or docs that I've read about this syntax.
My spidey sense is tingling and telling me that the better thing to do would be to copy the contents of the stream to some other object and then return that object to ensure that the stream is closed.
答案1
得分: 2
流将被关闭,如果它在try-with块内部返回。
此问题已经有人问过了,请参见此处:<br>
https://stackoverflow.com/questions/30643556/if-it-safe-to-return-an-inputStream-from-try-with-resource
英文:
The Stream will be closed, if it is returned inside the try-with block.
This question was already asked, see here:<br>
https://stackoverflow.com/questions/30643556/if-it-safe-to-return-an-inputstream-from-try-with-resource
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论