java 简单数据库连接池

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 简单数据库连接池

基础教程推荐