0

After we finish using resultset, normally i will do the following:

if(rs != null)
    rs.close();   rs = null;

What i want to ask is, by setting resultset = null like the following:

if(rs != null)
    rs = null;

Does it equals to setting rs.close()? Is there any chance that maximum cursor still occur?

hades
  • 4,294
  • 9
  • 46
  • 71
  • NO! It's not the same. You must close it. I don't get the second question though. – UDKOX May 18 '16 at 02:25
  • @Rudy Not duplication, my question is difference between resultset set null versus resultset close, the link you attached is why we need to close it. – hades May 18 '16 at 02:34

1 Answers1

1

Does it equals to setting rs.close()? Is there any chance that maximum cursor still occur?

No. They're not the same, and simply nulling the reference will not close the resources on your database. In fact, when the reference goes out of scope, it's unreachable (and thus nulled). So there isn't any need to explicitly null the reference. Also, note that without the braces your null assignment isn't attached to the if.

if (rs != null) {
    rs.close();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • sorry, i intended to put `rs = null;` same line with rs close – hades May 18 '16 at 02:29
  • Is setting resultset to null reduce the workload of GC? I mean, we can free up the memory little bit without having to wait for reference goes out of scope – hades May 18 '16 at 02:31
  • @hades No. It's equivalent to letting the variable go out of scope. It makes it *eligible* for GC (that doesn't necessarily invoke GC). – Elliott Frisch May 18 '16 at 02:33
  • @ElliottFrisch Oh! Really ? Isn't the collector working all the time ? The sooner you set it to null, the sooner it will be able to clean it, won't it ? – UDKOX May 18 '16 at 02:35
  • 1
    @UDKOX There are [many](http://stackoverflow.com/questions/1582209/java-garbage-collector-when-does-it-collect) ways to [answer](http://stackoverflow.com/questions/6909150/how-often-is-the-gc-executed) that question, but worrying about when (or if) the garbage collector will run is a micro-optimization (and you're probably better off if you [write dumb code](http://www.oracle.com/technetwork/articles/java/devinsight-1-139780.html)). – Elliott Frisch May 18 '16 at 02:40
  • 1
    @UDKOX It will be able to, but that doesn't mean it will. I'll sometimes null out a temporary resource if it's heavy and I need to do some more processing within the same scope. But it's usually unnecessary. – shmosel May 18 '16 at 02:40