Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Open Connection Objects

 
Puja Agarwal
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a small doubt in closing connection objects. If i close the connection objects directly without closing the PreparedStatement and ResultSet object in a method. Will the db connection object be closed or will it become a dangling object waiting for GC to run and claim them.

When i tried sometimes i get the connection object left open and sometimes it get closed. Why does it behaves like this..


hope i make sense


Thanks
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35279
384
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Puja,
It will usually be closed, but it depends on driver implementation. It is good practice to close all resources yourself though.
 
Scott Selikoff
author
Saloon Keeper
Posts: 4033
18
Eclipse IDE Flex Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a good practice to always close any database connection you open within a finally block. Leaving connections open is one of the biggest sources of memory leaks in large systems.
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have one small query :

Suppose i have the following hierarchy of declaration:

Connection Object
PreparedStatement
ResultSet

and following sequence of close :
PreparedStatement.close()
Connection close

i am not closing the resultSet, Can this cause memory leakage in JAVA?

i heard the if I close the preparedStatment, then result set will close automatically. Does this behavior is guaranteed ?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35279
384
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sunny Jain:
i heard the if I close the preparedStatment, then result set will close automatically. Does this behavior is guaranteed ?

Nothing is guaranteed. It depends on the implementation of the driver.

That said, most people have a utility method that closes all the resources. What's the harm in closing the ResultSet in that method too? It's only in one place after all.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic