zoukankan      html  css  js  c++  java
  • 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并发编程实战》龙果学院

  • 相关阅读:
    ios-app提交审核问题总结
    mui混合app请求过程处理(缓存、加载、刷新机制)
    vue引入assets和static静态资源问题
    mui入门教程
    scroll.js
    jQuery.Running.js
    CSS 编码技巧
    textillate.js
    3. 戏说VHDL之入门游戏一:流水灯
    2. 流水灯小计
  • 原文地址:https://www.cnblogs.com/pony1223/p/9461038.html
Copyright © 2011-2022 走看看