I want to use Apache Commons DBCP to enable connection pooling in a Java Application (no container-provided DataSource in this). In many sites of the web -including Apache site- the usage of the library is based in this snippet:
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
ds.setUsername("scott");
ds.setPassword("tiger");
ds.setUrl(connectURI);
Then you get your DB connections through the getConnection() method. But on other sites -and Apache Site also- the Datasource instance is made through this:
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI,null);
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory);
ObjectPool objectPool = new GenericObjectPool(poolableConnectionFactory);
PoolingDataSource dataSource = new PoolingDataSource(objectPool);
What's the difference between them? I'm using connection pooling with BasicDataSource
, or I need an instance of PoolingDataSource
to work with connection pooling? Is BasicDataSource
thread-safe (can I use it as a Class attribute) or I need to synchronize its access?
BasicDataSource is everything for basic needs. It creates internally a PoolableDataSource and an ObjectPool.
PoolableDataSource implements the DataSource interface using a provided ObjectPool. PoolingDataSource take cares of connections and ObjectPool take cares of holding and counting this object.
I would recommend using BasicDataSource. Only, If you really need something special maybe then you can use PoolingDatasource with another implementation of ObjectPool, but it will be very rare and specific.
BasicDataSource is thread-safe, but you should take care to use appropriate accessors rather than accessing protected fields directly to ensure thread-safety.