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.
Let's assume that:
- 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?
UPDATE:
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.
Short answer - Yes. For one, it's TERRIBLE coding practice just as it is in every other area of life to not clean up after yourself. For another, you can't predict whether the operating system is going to recognize that the java environment no longer needs the resources and you could end up having locks on files/etc that can't be released without a forced restart.
Always clean up whatever resources you open!
Update regarding your update to the original question - it takes 5 seconds to add a try/catch block to close any open resources, and can prevent you having to spend 5 minutes restarting your computer. Doing it right always saves time in the end. My dad always told me the true lazy person does things right the first time so they don't have to come back and do it again. I just say don't be lazy and do it right. The 5 seconds it takes to write a catch block will never slow down the writing process significantly... the 5 seconds you save by not writing it could slow down your debugging immensely.
If you not close the resources ,that may leads to application servers being frequently restarted when resource exhaustion occurs.because operating systems and server applications generally have an upper-bound limit for resources
According to docs
try-with-resources Statement introduced in java 7 for the programmers who hates close statements.
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.
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.