Java自己动手写连接池三,核心代码;
package com.kama.cn;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
public class ConnectionPool {
//数据库连接
private static ConnectionPool connectionPool=new ConnectionPool();
public List<Connection> poolList = new ArrayList<Connection>();
// 初始连接池大小
public int init_size = 10;
// 最大连接池大小
public int max_size = 30;
private ConnectionPool() {
/**
* 初始数据库连接池
*/
initdb();
}
public void initdb() {
for (int i = 0; i < init_size; i++) {
poolList.add(DBConfigUtil.getConn());
}
}
public Connection getConnection() {
Connection conn = null;
if (poolList.size() <= 0) {
poolList.add(DBConfigUtil.getConn());
}
conn = poolList.get(0);
poolList.remove(conn);
return conn;
}
/**
* 释放当前连接
*
* @param currentConn
*/
public void realseConnection(Connection currentConn) {
if (!poolList.contains(currentConn)) {
poolList.add(currentConn);
}
}
public static ConnectionPool getInstance()
{
if(connectionPool==null)
{
connectionPool=new ConnectionPool();
}
return connectionPool;
}
/**
* 连接池大小
* @return
*/
public int poolSize()
{
return poolList.size();
}
}