您的位置:首页 > 编程语言 > Java开发

36.自己写的一个开源连接池功能

2013-10-03 19:46 204 查看
public class ConnectionPool {
private LinkedList<Connection> pool;
private static String url = "jdbc:mysql://w.rdc.sae.sina.com.cn:3307/app_imu2b";
private static String saeAccessKey = null;
private static String saeSecretKey = null;
private static int maxCount = 200;
private static int currentCount = 50; // 因为初始的就是50个
public ConnectionPool() {
pool = new LinkedList<Connection>();
saeAccessKey = SaeUserInfo.getAccessKey();
saeSecretKey = SaeUserInfo.getSecretKey();
for (int i = 0; i < 50; i++) {
try {
Connection conn;
conn = DriverManager.getConnection(url, saeAccessKey,
saeSecretKey);
pool.addLast(conn);
} catch (SQLException e) {
throw new InitializeErrorException(e.getMessage());
}

}

}
public Connection getConnection() {
synchronized (ConnectionPool.class) {
Connection conn = null;
if (pool.size() > 0)
return pool.removeFirst();
else if (currentCount < maxCount) {
try {
conn = DriverManager.getConnection(url, saeAccessKey,
saeSecretKey);
currentCount++;
pool.addLast(conn);
} catch (SQLException e) {

}
return pool.removeFirst();
} else {
throw new ExceptionInInitializerError("SQL连接已经是最大值");
}

}

}
public void free(Connection conn) {
pool.addFirst(conn);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息