关闭资源总是很重要吗? [英] Is closing the resources always important?
问题描述
我多次遇到这样的声明:应用程序应该始终显式关闭它打开的所有资源。
Many times I met the statement that the application should always explicitly close all the resources that it opened.
我的编程方法相当务实而且我没有喜欢盲目地遵循任何我不明白的好处。因此我的问题。
My approach to programming is rather pragmatic and I don't like to blindly follow any convention that I don't clearly see benefits of. Hence my question.
让我们假设:
- 我有一个小应用程序
- 它会打开一些资源(例如文件,数据库连接,远程流)并对其进行处理
- 它可以工作几分钟然后退出
- 让我们说它是Java语言(如果语言相关)
- I have a small application
- It opens a few resources (e.g. files, database connections, remote streams) and processes it
- It works a few minutes and then it exits
- Let's say it's in Java (if the language is relevant)
我真的需要关心关闭我打开的所有资源?我猜我打开的所有资源都将在应用程序/虚拟机退出时关闭/释放。我是对的吗?
Do I really have to care about closing all the resources that I opened? I guess all the resources I opened will be closed/released when the application/virtual machine exits. Am I right?
如果这是真的,有没有令人信服的理由关心在如此短小的工作申请中关闭资源?
If that's true, are there any convincing reasons to care about closing resources in such small, short working application?
更新:
这个问题纯属假设,但不关心的论点是我可能只是黑客攻击一些快速脚本,不想编写与手头问题没有直接关系的任何不必要的代码:关闭资源,完成所有这些冗长的try-catch-finally内容,处理我不关心的异常等。
The question is purely hypothetical, but the argument for not caring about that is that I may be just hacking together some quick script and don't want to write any unnecessary code not directly related to the problem at hand: closing resources, doing all this verbose try-catch-finally stuff, handling exceptions that I don't care about etc.
问题的关键在于是否存在任何实际后果。
The point of the question is whether there are any practical consequences of not doing it.
推荐答案
我猜我打开的所有资源都将在应用程序/虚拟机退出时关闭/释放。
I guess all the resources I opened will be closed/released when the application/Virtual machine exits.
未经过定期发布的资源会发生什么事情是您无法控制的。它可能没有坏处,也可能会有所作为。它也是高度依赖平台的,所以只测试一个也无济于事。
What happens with a resource which was not regurarly released is out of your control. It may do no harm, or it may do some. It is also highly platform-dependent, so testing on just one won't help.
我为什么要关心这些资源的关闭小而短的工作申请?
why should I care about closing these resources in such small, short working application?
应用程序的大小无关紧要。首先,应用程序通常会增长第二,如果你没有以正确的方式练习,你就不会知道如何做到这一点。
The size of the application shouldn't matter. First, applications usually grow; second, if you don't practice doing it the right way, you won't know how to do it when it matters.
这篇关于关闭资源总是很重要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!