代码细节优化:
- package cn.itcast.jdbc.datasource;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.LinkedList;
- import java.util.List;
- public class MyDataSource {
-
- private static String url="jdbc:mysql://localhost:3306/jdbc";
- private static String user="root";
- private static String password="admin";
- private static int initCount=5;
- private static int maxCount=10;
- private int currentCount=0;
- private LinkedList<Connection> connectionsPool=new LinkedList<Connection>();
-
- public MyDataSource(){
- for(int i=0;i<initCount;i++){
- try {
- //先入先出的算法
- this.connectionsPool.addLast(this.createConnection());
- this.currentCount++;
- } catch (SQLException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
- }
-
- public Connection getConnection() throws SQLException{
- synchronized(connectionsPool){
- if(connectionsPool.size()>0)
- return this.connectionsPool.removeFirst();
- if(this.currentCount<maxCount){
- this.currentCount++;
- return this.createConnection();
- }
- throw new SQLException("已没有连接!");
- }
- }
- private Connection createConnection() throws SQLException{
- return DriverManager.getConnection(url, user, password);
- }
-
- public void free(Connection conn){
- this.connectionsPool.addLast(conn);
- }
- }
多线程并发问题、并发获取连接可能会出现安全问题,需要给代码加上同步块,使其串行获取连接,即加上锁。
阅读(965) | 评论(0) | 转发(0) |