Database connection pooling is not a new concept. Typically, one would want to apply this concept into their application when dealing with database connections. The old style of creating database connections from scratch, maintaining them and closing them upon finishing the request is a very expensive process and takes a heavy load on the server itself.

Apache Tomcat supports connection pooling. One advantage of pooling is that it reduces the garbage collection load. Using connections objects that are in the pool, we do not need to worry about memory leaks of sort.

Once we request a connection and close it, the connection object will be sent back to the pool and wait for other requests. Hence, we are actually going to use existing connection objects. If the pool has ran out of connection objects, it will create a new one and adds it up to the total number of connections inside the pool.

To enable connection pooling in java, you only need to add this tag in the context.xml in the conf/ folder of apache tomcat’s working folder.

<Resource name="jdbc/dbname"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
username="micmic"
password="micmic"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/dbname"
maxWait="1000"
removeAbandoned="true"
maxActive="30"
maxIdle="10"
removeAbandonedTimeout="60"
logAbandoned="true"/>

This tag must be inside the <context> tag.

To use this connection, you can have a method that looks similar to this

public static Connection getConnection() throws Exception {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/dbname");
ds.getConnection();
}

And use that same method to get a connection object from the pool:

Connection con = getConnection();

When you close this connection object after use, it will not close the object and garbage collect. Rather, it puts it back in the pool for the next use.

Please note that this sample code uses the MySQL Database. If you use other databases, check the appropriate driver class for the JDBC driver and make sure that you include the JDBC driver library in Apache Tomcat’s lib/ folder.

Related Posts Plugin for WordPress, Blogger...