Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to use finally to close resources?

Most of the time, the only thing I see a finally block used for is something like

FileInputStream f;
try{
    f= new FileInputStream("sample.txt");
    //something that uses f and sometimes throws an exception
}
catch(IOException ex){
    /* Handle it somehow */
}
finally{
    f.close();
}

My question is, if f's scope ends with the enclosing block, why do we need to close it in the finally?

like image 203
Matt G Avatar asked Oct 04 '11 17:10

Matt G


3 Answers

Because garbage collection is not the same thing as resource cleanup.

For example, if you have a JDBC Connection object that goes out of scope, there's no signal sent to the database server to indicate that open cursors and connections are no longer needed. Without those messages, you'll eventually exhaust the number of cursors and connections available to you.

Same with file handles and any other resource. Clean up after thyself.

like image 134
duffymo Avatar answered Nov 19 '22 22:11

duffymo


Well you've given a bad example - I suspect you meant something like FileInputStream - but the basic reason is that Java doesn't have deterministic finalization.

The scope of the variable f ends with the block it's declared in (not the try block), but that doesn't mean there are necessarily no "live" references to the object any more - and the garbage collector will neither finalize the object nor garbage collect it in any deterministic manner.

Unless you want to leave resources hanging around for an arbitrary length of time (and delay garbage collection, as finalizers require an extra round of collection before the memory is finally released), you should explicitly close resources.

Basically Java does not support RAII in the same way that C++ does; you shouldn't try to use it as if it were C++.

like image 30
Jon Skeet Avatar answered Nov 19 '22 23:11

Jon Skeet


because finally is called everytime, even if you get an exception raised. the finally block insure you that the file/connection will be closed.

like image 2
Cygnusx1 Avatar answered Nov 19 '22 21:11

Cygnusx1