Java线程通信-简单的连接池实例


1.简单连接池实例

public class DataSourcePool {
    private LinkedList<Connection> pool = new LinkedList<Connection>();
    private int COUNT_INIT;          //初始化连接数
    private int COUNT_MAX;          //最大连接数
    private volatile int COUNT_CURRENT = 0;       //当前连接数量
    private String DRIVER_CLASS;
    private String URL;
    private String USER_NAME;
    private String PASSWORD;
    private Lock lock = new ReentrantLock();
    private Condition c = lock.newCondition();

    public DataSourcePool(Properties properties) {
        COUNT_INIT = Integer.parseInt(properties.getProperty("initialSize"));
        COUNT_MAX = Integer.parseInt(properties.getProperty("maxActive"));
        DRIVER_CLASS = properties.getProperty("driverClass");
        URL = properties.getProperty("url");
        USER_NAME = properties.getProperty("userName");
        PASSWORD = properties.getProperty("password");
        try {
            Class.forName(DRIVER_CLASS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        for(int i=0;i<COUNT_INIT;i++){
            try {
                pool.add(DriverManager.getConnection(URL,USER_NAME,PASSWORD));
                COUNT_CURRENT++;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //获取连接
    public Connection getConnection(){
        Connection result = null;
        lock.lock();
        try {
            while (pool.isEmpty() && COUNT_CURRENT >= COUNT_MAX) {
                c.await();          //如果连接池为空且连接数已经达到最大则等待
            }
            if (pool.isEmpty()&&COUNT_CURRENT < COUNT_MAX) {
                result = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
                COUNT_CURRENT++;
            }
            else{
                result = pool.removeLast();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        finally{
            lock.unlock();
        }
        return result;
    }

    //释放连接
    public void release(Connection connection){
        lock.lock();
        try {
            if(pool.size()<COUNT_INIT){
                pool.push(connection);
                c.signal();
            }
            else{
                connection.close();
                COUNT_CURRENT--;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        finally{
            lock.unlock();
        }
    }
}

文章作者: Bryson
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Bryson !
评论
 上一篇
下一篇 
  目录