高并发下单例的jdbc连接池工具类

package com.mlt.util;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.mlt.pojo.ExceptionCode;
import com.mlt.pojo.GlobalException;
import com.mysql.jdbc.Connection;

public class  JdbcUtil {

        private String url="";
        private String userName="";
        private String pas="";
        private static final String name = "com.mysql.jdbc.Driver";
        /**
         * 初始连接池大小
         */
        private static int initCount = 10;
        /**
         * 连接池最大
         */
        private static int maxCount = 20;
        private int currentCount = 0;
        private  volatile static  JdbcUtil jdbcUtil= null;
        LinkedList connectionPool = new LinkedList();


        /**
         * 私有构造函数
         * @param url
         * @param userName
         * @param pas
         */
        private JdbcUtil(String url,String userName,String pas) {
            this.url=url;
            this.userName=userName;
            this.pas=pas;
            try {
                for (int i = 0; i < initCount; i++) {
                    this.connectionPool.addLast(this.createConnection());
                    this.currentCount++;
                }
            } catch (SQLException | ClassNotFoundException e) {
                throw new ExceptionInInitializerError(e);
            }
        }


        /**
         * 获取连接
         * @return
         * @throws SQLException
         * @throws ClassNotFoundException
         */
        public Connection getConnection() throws SQLException, ClassNotFoundException {
            synchronized (connectionPool) {
                if (connectionPool.size() > 0)
                    return connectionPool.removeFirst();

                if (this.currentCount < maxCount) {
                    this.currentCount++;
                    return createConnection();
                }
                throw new SQLException("已没有链接");
            }
        }

        /**
         * 释放连接
         * @param conn
         */
        public void free(Connection conn) {
            connectionPool.addLast(conn);
        }


        /**
         * 创建连接
         * @return
         * @throws SQLException
         * @throws ClassNotFoundException
         */
        private Connection createConnection() throws SQLException, ClassNotFoundException {
            Class.forName(name);// 指定连接类型
            return (Connection) DriverManager.getConnection(url,userName, pas);
        }



        public static JdbcUtil getJdbcUtil(String url, String user, String password) {
            if(jdbcUtil==null) {
            synchronized (JdbcUtil.class) {
                if(jdbcUtil == null) {
                    jdbcUtil = new JdbcUtil(url,user,password);
                }
              }
            }
            return jdbcUtil;
        }
}

你可能感兴趣的:(jdbc)