Wednesday, June 09, 2010

Apache Commons DBCP and initial pool size

Unless you are using BasicDataSource, DBCP does not provide an initial pool size, which is very important if you want to avoid pool expansion out of sudden. It is particularly important if you are migrating from C3P0, like what I did recently. So, in this case, you will have to code an initializer to do it for you. In my case, I wrote a static method that is invoked through Spring:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool.ObjectPool;

public class DataSourceInitializer {
    private static final Log log = LogFactory.getLog(DataSourceInitializer.class);

    public static void init(ObjectPool pool, int initialSize, String dataSourceName) {
        int count = 0;"Initializing connections for data source: " + dataSourceName);

        for (int i = 0; i < initialSize; i++) {
            try {
            catch (Exception e) {
                log.warn("Failure to initialize connection.", e);
        }"Initialized " + count + " out of " + initialSize
                + " connections for data source: " + dataSourceName);
And, in Spring, I call it like this:
<bean id="dataSourceInitializer"
       <property name="staticMethod"
           value="com.example.DataSourceInitializer.init" />
       <property name="arguments">
               <ref bean="objectPool" />
               <ref bean="databasePoolSize" />
Post a Comment