我在看李勇老师讲的JDBC视频,这是jdbc连接池,他说数据库连接数有限制,然后就定义了maxCount最大连接数这个值,需要知道当前连接数所以又定义了一个currentCount,但是new一个MyDataSource类的时候不是就创建了5个连接了吗,那这里this.currentCount < maxCount的话currentCount不应该*5吗?还有个问题就是我这样写为什么有错
我的代码
public Connection getConnection(){
synchronized (connectionsPool) {
if (this.connectionsPool.size() > 0)
return this.connectionsPool.removeFirst();
}
}
---------------------------------------------------------------------------------------------------
public class MyDataSource {
private static String url = "jdbc:mysql://localhost:3306/jdbc";
private static String user = "root";
private static String password = "";
private static int initCount = 5;
private static int maxCount = 10;
private int currentCount = 0;
LinkedList<Connection> connectionsPool = new LinkedList<Connection>();
public MyDataSource() {
try {
for (int i = 0; i < initCount; i++) {
this.connectionsPool.addLast(this.createConnection());
this.currentCount++;
}
} catch (SQLException e) {
throw new ExceptionInInitializerError(e);
}
}
public Connection getConnection() throws SQLException {
synchronized (connectionsPool) {
if (this.connectionsPool.size() > 0)
return this.connectionsPool.removeFirst();
if (this.currentCount < maxCount) {
this.currentCount++;
return this.createConnection();
}
throw new SQLException("已没有链接");
}
}
public void free(Connection conn) {
this.connectionsPool.addLast(conn);
}
private Connection createConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
}
------解决方案--------------------
正常一个MyDataSource,不能是用的时候就new一个,这样不乱套了