public class DataSourcePool {private final CopyOnWriteArrayListConnection list;//用到了信号量private final Semaphore semaphore;public DataSourcePool(int size) throws SQLException {list = new CopyOnW...
public class DataSourcePool {
private final CopyOnWriteArrayList<Connection> list;
//用到了信号量
private final Semaphore semaphore;
public DataSourcePool(int size) throws SQLException {
list = new CopyOnWriteArrayList<>();
semaphore = new Semaphore(size);
for (int i=0;i<size;i++){
Connection connection = DriverManager.getConnection("url");
list.add(connection);
}
}
//使用同步方法获取
public synchronized Connection getConnection() throws InterruptedException {
//先将当前信号量-1,如果为0,将阻塞
semaphore.acquire();
return list.remove(0);
}
public synchronized void close(Connection connection){
//信号量+1
semaphore.release();
list.add(connection);
}
沃梦达教程
本文标题为:java 简单数据库连接池
基础教程推荐
猜你喜欢
- 详解Java中static关键字的使用和原理 2023-06-16
- Spring的IOC原理详情 2023-02-27
- JSP 中Servlet的自己实现 2023-07-31
- 解读SpringBoot接收List<Bean>参数问题(POST请求方式) 2023-05-25
- Java多线程案例之阻塞队列详解 2023-06-17
- Java检查日期字符串是否合法的方法总结 2023-06-06
- Java中四种引用详解 2023-08-11
- SpringBoot工程打包与运行的实现详解 2023-03-07
- 如何使用mybatis-plus实现分页查询功能 2023-01-23
- ExecutorService实现获取线程返回值 2023-04-12