日期:2014-05-16  浏览次数:20399 次

DBCP学习-多个不受控制的连接池
https://issues.apache.org/jira/browse/DBCP-342

DBCP-93 DBCP-339 DBCP-342 都是同一个问题

问题描述:
在常见connectionPool的时候,由于SQLException(例如密码错误等)导致在王connectionPool添加连接的时候发生异常,旧的处理时直接抛出,不会返回
在下一次调用getConnection的时候依旧会发生这个问题,但是connectionPool是一个GenericObjectPool,connectionPool.addObject()添加连接失败,connectionPool这个对象本身还是存在的,因为createConnectionPool方法每次是会创建一个新的GenericObjectPool用来赋给connectionPool,这样上一次创建的connectionPool就成了orphaned connectionPool

而connectionPool本身有一个Evictor TimerTask,这个任务会调用ensureMinIdle()确保最小空闲的连接个数,如果不够则会继续创建

Once the database is back up, all these orphaned connectionPool's evitor threads will attempt to created minIdle connections to the database. This exhausts the max num connections on the database.

当数据库恢复正常时,所有创建的connectionPool都会去连接数据库,从而导致创建大量连接,也可能导致数据库挂掉

解决方法:
try {
                for (int i = 0 ; i < initialSize ; i++) {
                    connectionPool.addObject();
                }
            } catch (Exception e) {
                closeConnectionPool();
                throw new SQLException("Error preloading the connection pool", e);
            }

在抛出异常后 将connectionPool关闭,从而不会产生孤立的连接池(orphaned connectionPool)