3

Consider the following code snippet:

public void getUsers() {
    CachedRowSet rowSet = new CachedRowSetImpl();
    .........     /* Initialize the rowset */
    String query = "SELECT user_id FROM users";
    rowSet.setCommand(query);
    rowSet.execute();
    .........    /* Do some job */

}

Here the CachedRowSet object is used locally in a method. Do I need to manually close it here or the contents it holds will be grabage collected automatically when the method finishes?

Rafi Kamal
  • 4,522
  • 8
  • 36
  • 50
  • 3
    If there are absolutely no other references to it, it will be a candidate for garbage collection the next time garbage collection is performed; that won't necessarily happen when the method finishes, though. Does it cost you anything to close it? – Anthony Grist Sep 05 '12 at 09:32

1 Answers1

4

from: http://docs.oracle.com/javase/1.5.0/docs/api/javax/sql/rowset/CachedRowSet.html

A CachedRowSet object is a disconnected rowset, which means that it makes use of a connection to its data source only briefly. It connects to its data source while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, a CachedRowSet object is disconnected, including while its data is being modified. Being disconnected makes a RowSet object much leaner and therefore much easier to pass to another component. For example, a disconnected RowSet object can be serialized and passed over the wire to a thin client such as a personal digital assistant (PDA).

that means there is no connection issue to close so u can leave it

but i think its good practice to always close what you open and not leave it to the GC which you usually don't touch or tell when to run.

given a large enough server with many requests, if it causes open file descriptors it can eventually be an issue. making sure resources are closed is always best

yael alfasi
  • 692
  • 1
  • 4
  • 13