关闭资源总是重要的吗? [英] Is closing the resources always important?

查看:26
本文介绍了关闭资源总是重要的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多时候我遇到过这样的说法,即应用程序应该始终明确关闭它打开的所有资源.

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.

假设:

  1. 我有一个小应用
  2. 它打开一些资源(例如文件、数据库连接、远程流)并对其进行处理
  3. 它工作几分钟然后退出
  4. 假设它是用 Java 编写的(如果语言相关)

我真的需要关心关闭我打开的所有资源吗?我猜我打开的所有资源都会在应用程序/虚拟机退出时关闭/释放.我说得对吗?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆