JAVA写简单的数据库连接池
创建数据库连接以及关闭连接是很耗费时间的,并且数据库支持的连接数量也是有限的,当数据库的连接数量达到上限的时候,后续的连接就会失败。因此这里引入了数据库缓冲池。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | public class ConnecionPool { private int size; List<Connection> connections = new ArrayList<>(); public ConnecionPool( int size){ this .size=size; init(); } public void init(){ try { Class.forName( "com.mysql.jdbc.Driver" ); while (size--!= 0 ){ connections.add(DriverManager.getConnection(jdbc:mysql: //127.0.0.1:3306/d数据库名称, 用户名,密码)// ); } } catch (Exception e){ e.printStackTrace(); } } public Connection getConnection(){ try { //如果没有连接了,线程就等待 while (connections.isEmpty()){ this .wait(); } } catch (Exception e){ e.printStackTrace(); } return connections.remove( 0 ); } public void returnConntion(Connection connection){ connections.add(connection); this .notifyAll(); } } |