Java并发编程原理与实战二十四:简易数据库连接池
Posted 屌丝码农
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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并发编程实战》龙果学院
以上是关于Java并发编程原理与实战二十四:简易数据库连接池的主要内容,如果未能解决你的问题,请参考以下文章
Java并发编程原理与实战二十六:闭锁 CountDownLatch