• Java并发编程原理与实战二十四:简易数据库连接池


    public class MyDataSource {
    
        private static LinkedList<Connection> pool = new LinkedList<>();
    
        private static final int INIT_CONNECTIONS = 10;
    
        private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
    
        private static final String URL = "";
    
        private static final String USER = "";
    
        private static final String PASSWORD = "";
    
        static {
            try {
                Class.forName(DRIVER_NAME);
                for (int i = 0; i < INIT_CONNECTIONS; i++) {
                    Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
                    pool.addLast(connection);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public Connection getConnection() {
            synchronized (pool) {
                while (pool.size() <= 0) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
    
                if (!pool.isEmpty()) {
                    return pool.removeFirst();
                }
            }
            return null;
        }
    
        public void releaseConnection(Connection connection) {
            if (connection != null) {
                synchronized (pool) {
                    pool.addLast(connection);
                    notifyAll();
                }
            }
        }
    }

    参考资料:

    《java并发编程实战》龙果学院

  • 相关阅读:
    39页第3题 求x的n次幂
    实验4-1 求花费电费的金额
    实验二利用循环计算多个圆柱体体积
    39页第一题 四则运算及其余数
    实验一计算圆的面积
    7-14
    第六章例6-3
    第六章例6-2
    第六章例6-1
    第五章例5-9
  • 原文地址:https://www.cnblogs.com/pony1223/p/9461038.html
Copyright © 2020-2023  润新知