以前认为连接池,线程池这些东西很高端。因为出了问题之后,总是有人说这个连接池/线程线的配置不对嘛,应该..... 今天学习了下,这个池到底应该怎么设计。发现apache的common-pool早就思考过这个问题了,并且定义了一个规范和框架。基于此我学习了些资料来写一个数据库连接池。
先写个测试程序,多线程不停的拿连接与释放连接,取到连接就打印一下连接id。如果同一个id,出现多次,则证明这个连接被复用了。
1.测试程序
public class TestJDBCPool {
public static void main(String[] args) {
//初始化,实际可用spring初始化
JDBCPool pool=new JDBCPool("jdbc:mysql://localhost:3306/test","root","xx","com.mysql.jdbc.Driver",null);
try {
for (int i = 0; i < 200; i++) {
new Thread(new PoolTestThread(pool)).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static class PoolTestThread implements Runnable {
private JDBCPool pool;
public PoolTestThread(JDBCPo