wood burning stoves 2.0*
The moose likes JDBC and the fly likes idiom for finally closing resources Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "idiom for finally closing resources" Watch "idiom for finally closing resources" New topic
Author

idiom for finally closing resources

Michael Zellmann
Greenhorn

Joined: Dec 17, 2004
Posts: 18
I want to dependably close the data base resources used in my application, despite exceptions. I also want to do this with sensible, clean code. The finally block seems critical, as well as avoiding duplication. Below is my current thought on how to do this, but I am not sure if it is good practice. I would welcome any suggestions from more experienced programmers.
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30789
    
157

Michael,
Assigning it to null is unnecessary as the variables go out of scope immediately after anyway. Other than that, you have the idiom down.

Two things people do to make this work even better:
1) Create a utility class that has a method like DbUtils.close(rs,stmt,conn). This lets the idiom exist in only one place.
2) Have the code in a superclass with an abstract method just to implement the executeQuery/loop through result set parts.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Agreed, although:

1) the catch is not required and the try/finally is valid (and sometimes preferred) without it
2) The inner try/catch should catch SQLException, not 'Exception'
3) I like to log the inner exception in case it causes resource leaks, but I'm not too strict on this.
Scott Selikoff
author
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3712
    
    5

I went through a similar tirade not long ago in my blog. Generally, I prefer "if (null != rs) try { rs.close(); } catch (Exception e) {}" in the form of reusable static method.

Granted, you don't actually need to check if rs is null, although its good to. Changing the value to null in the finally is clever for garbage collection, but shouldn't be needed. 99.99% of the time, I create, use, and throw away ResultSets in a single method call so I can't see them ever hanging around such that they wouldn't be garbage collected.
[ December 16, 2008: Message edited by: Scott Selikoff ]

My Blog: Down Home Country Coding with Scott Selikoff
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: idiom for finally closing resources