users@glassfish.java.net

getNonTxConnection

From: <glassfish_at_javadesktop.org>
Date: Mon, 03 Aug 2009 07:50:43 PDT

I have inherited a collection of rest web services and have found one that is leaking JDBC connections thanks to the connection leak detection in Glassfish. While reviewing that code I noticed that it calls DataSource.getNonTxConnection(). Reading the docs and googling it a bit leads me to believe that the code should probably not be calling that. I'm thinking that it should be contained in a transaction to contain the business process the web service is doing. Using it seems like it would expose the process to dirty data. The process in question is reading data from several places (mostly just doing reports). It's a guess, but it's possible the person who coded this originally read the docs on getNonTxConnection() and thought it would speed things up.

Could someone more experienced with this explain the reasoning behind using or not using getNonTxConnection()?

Second question, about the second code snippet: Why is that one leaking?

Thanks,
Jim


The code in question looks like:
[code]
        InitialContext ctx = new InitialContext();

        DataSource ds = (DataSource) ctx.lookup(jdbc_resource);
        Connection con = ds.getNonTxConnection();
        Connection drivercon = ds.getConnection(con);

        PreparedStatement ps = drivercon.prepareStatement(query);

        // if the query has a problem, obviously the leak is caused here (in my case, the
        // database kills long-running queries, throwing an exception here)
        ResultSet results = ps.executeQuery();
        Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();

        try {
            //do stuff with results
            results.close();
            ps.close();
        }
        catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        finally{
            con.close();
        }

        return map;
[/code]




Here's another case where a leak was detected, but I don't understand why:
[code]
        InitialContext ctx = new InitialContext();

        DataSource ds = (DataSource) ctx.lookup(jdbc_resource);
        Connection con = ds.getNonTxConnection(); // leak is detected here, why?
        Connection drivercon = ds.getConnection(con);

        try{
            PreparedStatement ps = drivercon.prepareStatement();
            ps.executeUpdate();
            //do stuff
        }
        catch (Exception ex){
            throw ex;
        }
        finally{
            con.close(); // should it be closing driverCon instead?
        }
[/code]
[Message sent by forum member 'culli' (culli)]

http://forums.java.net/jive/thread.jspa?messageID=358617