Skip to content
 

Managing database connections – DataSource connection pooling

So following on from the last post – I’ve now employed a simple but essential technique called connection pooling, using a DataSource, in the project. A DataSource is an abstract java class that was created for those writing JDBC drivers to extend in order to provide a developer a highly extensible way of interacting with databases.

Or put simply, nearly all JDBC drivers should have a DataSource class that enables you to do clever stuff like manage the number of concurrent connections to a database. I took me a while to figure out how to employ a datasource connection pool. The best way for a netbeans project is to look at the server help on how to use datasources – if you’re using Apache Tomcat or Sun’s Glassfish you simply alter the web and context xml files. You just need to tailor it to your database parameters and make sure that the JDBC driver is in the imported libraries. This is essentially makes use of JNDI which gives you an easy way to say- I need a datasource instance and some connections from it!

The relevant code to make use of a DataSource once defined goes something like:

InitialContext cxt = new InitialContext();
        if ( cxt == null ) {
            throw new Exception(“Uh oh — no context!”);
        }

        DataSource ds = (DataSource) cxt.lookup( “java:/comp/env/jdbc/postgres” );

        if ( ds == null ) {
            throw new Exception(“Data source not found!”);
        }

[And to get the connection:]  Connection myConn = ds.getConnection();

Your server / application container will now manage the number of connections, when the maximum is reached the oldest connection gets dropped. This inevitably improves the performance of your application by reducing concurrent connections – you can simply pass the DataSource between your methods and use it to request a connection when necessary. This ensures no connection leakage and ultimately reduces the possibilty that your database will become overloaded and things will all go bad.

Additionally it improves performance, you just need to be sure to set a reasonable minimum, maximum and increment of connections. This should be appropriate to your application so take into consideration roughly how many connections you need per instance of the DataSource. Also when done with a connection wherever possible use a finally of a try/catch/finally block to close the connection and any prepared statements.

In short its dramatically improved the response times of our project and now never overloads the SQL database. It’s all very much an appropriate way to use the more advanced features of the J2EE platform. For a few extra lines of code, the benefit is definately worth it – and that’s the idea of J2EE development – making complex development more modular and easier to implement. Having said this its worth remembering J2EE solutions can be overkill for simple web software.

Leave a Reply