package cn.itcast.jdbc.dataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
public class MyDataSource {
private static String url = "jdbc:mysql://localhost:3306/jdbc";
private static String user = "root";
private static String password = "123456";
private static int initCount=5;
private static int maxCount=10; //最大连接数,避免创建太多连接影响效率
private int currentCount=0;
public static void main(String[] args) {
}
private LinkedList<Connection> connectionPool = new LinkedList<Connection>(); // 连接池
public MyDataSource() {
try {
for (int i = 0; i < initCount; i++) { // MyDataSource创建时就建立5个连接
this.connectionPool.addLast(this.createConnection());
this.currentCount++;
}
} catch (SQLException e) {
throw new ExceptionInInitializerError();
}
}
public Connection getConnection() throws SQLException {
synchronized (connectionPool) { // 确保多个线程不会取到同一个连接
if (this.connectionPool.size() > 0)
return this.connectionPool.removeFirst();
if(this.currentCount<maxCount){ //当当前连接数小于最大连接数,创建新连接
this.currentCount++;
return this.createConnection();
}
throw new SQLException("已经没有可用连接");
}
}
public void free(Connection conn) { // 释放连接,实际上就是重新加入到连接池
this.connectionPool.addLast(conn);
}
private Connection createConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
}
连接池优化
最新推荐文章于 2020-07-06 21:36:26 发布