javadatabasejdbccachedrowset

Should I always close a CachedRowSet even if it goes out of scope?


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?


Solution

  • 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 you can leave it.

    However, I think it's a 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.