清理 C3P0 PooledDataSources

最简单的清理c3p0 PooledDataSources的方法就是调用DataSources类的destroy方法。

只有PooledDataSource对象需要被清理,而DataSources不需要。

对非池化或非c3p0的数据源调用destory(…)方法也没有什么影响。try { DataSource ds_unpooled = DataSources.unpooledDataSource("jdbc:postgresql://localhost/testdb", "swaldman", "test-password"); ds_pooled = DataSources.pooledDataSource(ds_unpooled); // do all kinds of stuff with that sweet pooled DataSource... } finally { DataSources.destroy(ds_pooled); }另外,c3p0的PooledDataSource接口有一个close()方法,你可以调用它来关闭DataSource对象。

所以你可以通过这个方法来使把DataSource对象转换成一个PooledDataSource对象然后关闭它。static void cleanup(DataSource ds) throws SQLException { // make sure it's a c3p0 PooledDataSource if (ds instanceof PooledDataSource) { PooledDataSource pds = (PooledDataSource) ds; pds.close(); } else System.err.println("Not a c3p0 PooledDataSource!"); }未被引用的 PooledDataSource实例不会在被用户关闭它之前通过垃圾回收器调用它的finalize()而被关闭。

就像我们知道的那样,自动销毁机制应该只能成为一种辅助方法,而不要用其来确保资源的清理。

REF:
http://cwiki.ossez.com/pages/viewpage.action?pageId=4719795