java基础--jdbc--各种池的实现--02

程序设计中,通常会涉及各类池,如锁池,等待池,jdbc数据库连接池。

下面以数据库连接池来展示各种池的实现:

1.利用LinkedList数据结构来来保存池中的应用对象。

2.为了保证并发请求对池的访问,对池设置同步操作了。

3.对池的容量进行设定。兼容以前池中对象的操作方式,满足池中对象以前的使用方式,但又不影响到池,通过代理实现。

4. 组合优先于继承。

public class MyDataSource {
 private static String url = "jdbc:mysql://localhost:3306/jdbc";
 private static String user = "root";
 private static String password = "";

 private static int initCount = 5;
 private static int maxCount = 10;
 private int currentCount = 0;

 LinkedList<Connection> connectionsPool = new LinkedList<Connection>();

 public MyDataSource() {
  try {
   for (int i = 0; i < initCount; i++) {
    this.connectionsPool.addLast(this.createConnection());
    this.currentCount++;
   }
  } catch (SQLException e) {
   throw new ExceptionInInitializerError(e);
  }
 }

 public Connection getConnection() throws SQLException {
  synchronized (connectionsPool) {
   if (this.connectionsPool.size() > 0)
    return this.connectionsPool.removeFirst();

   if (this.currentCount < maxCount) {
    this.currentCount++;
    return this.createConnection();
   }

   throw new SQLException("已没有链接");
  }
 }

 public void free(Connection conn) {
  this.connectionsPool.addLast(conn);
 }

 private Connection createConnection() throws SQLException {
  return DriverManager.getConnection(url, user, password);
 }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值