Java实现一个简易的数据连接池

xiaoxiao2021-02-28  32

Java实现一个简易的数据连接池

下面给出了代码,设置数据连接池的初始大小INIT_CONNECTIONS=10,首先在静态代码块中加载驱动,在Datapool()函数中初始化数据连接池,getConnect()函数为返回数据连接池中的连接,若没有可用的,则等待。release()函数为将用完的连接返回给连接池。

package com.concur.threadpool; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.LinkedList; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Datapool { private LinkedList<Connection> pool=new LinkedList<>(); private final int INIT_CONNECTIONS=10; private static final String DRIVER_CLASS=""; private final String USER =""; private final String PASSWORD=""; private final String URL=""; private Lock lock=new ReentrantLock(); private Condition c=lock.newCondition(); static{ try { Class.forName(DRIVER_CLASS); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public Datapool(){ for(int i=0;i<INIT_CONNECTIONS;i++){ try { Connection conn=DriverManager.getConnection(URL, USER, PASSWORD); pool.addLast(conn); } catch (SQLException e) { e.printStackTrace(); } } } public Connection getConnect(){ Connection result=null; lock.lock(); try{ while(pool.size()<=0) { try { c.await(); } catch (InterruptedException e) { e.printStackTrace(); } } if(!pool.isEmpty()){ result=pool.removeFirst(); } return result; }finally{ lock.unlock(); } } public void release(Connection conn){ if(conn!=null){ lock.lock(); try{ pool.addLast(conn); c.signal(); }finally{ lock.unlock(); } } } }
转载请注明原文地址: https://www.6miu.com/read-2800284.html

最新回复(0)