views:

62

answers:

2

pseudo code to explain my self better. I'm learning Java at this point in time.

if I have a method

public resultSet getEverything() 
{    
   resultSet rs = blabla;    
   return rs 
}

I can't rs.close() as I need to use it in the method I retrieve it hence then I will use it, and maybe 'close' the new resultSet I create.

What happens from the previous resultSet? Is it left to be collected by the garbage collector? Does it close itself when I close the 'new' resultSet? Does it have any impact on code efficiency/performance?

Any feedback would be greatly appreciated :) as this has confused me a bit. It is more of an OOP question rather than Java I think. Thanks!

A: 

You should not be returning a java.sql.ResultSet from a method. It should always be created, mapping into an object or data structure, and closed in the scope of the method in which it was created in a finally block.

A java.sql.ResultSet is associated with a database cursor, a scarce resource. You don't want to keep those open for a long time.

Garbage collectors do not clean up result sets, statements, or connections to databases. It will remove the reference from memory, but the cursor or connection will still be open on the database side. It's your responsibility to close them properly or you'll exhaust the supply.

An object, data structure, or CachedRowSet is the right thing to return.

duffymo
A: 

There's only one resultSet here. You create it and return it in this method; the calling method (the one that calls getEverything()) now has it - it doesn't have a copy, or anything like that; it has the resultSet you create in this method. But the calling method must assign the result of getEverything() if it is to close it - like this:

resultSet rs = getEverything();

versus simply calling the method like this:

getEverything();

In the second case, the result set would be created, then made available to the behind-the-scenes garbage collector (essentially, deleted) without an opportunity to close it.

Carl Manaster
thanks.. you made it really clear :) On the other hand it is also interesting, what duffymo has pointed out in his reply... its better if you close any connections to DB in the same method.
Nicholas