Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2161144
  • 博文数量: 556
  • 博客积分: 11457
  • 博客等级: 上将
  • 技术积分: 5973
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-24 22:33
文章分类

全部博文(556)

文章存档

2013年(22)

2012年(74)

2011年(460)

分类: Java

2011-10-05 21:18:11

代码细节优化:

  1. package cn.itcast.jdbc.datasource;

  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import java.util.LinkedList;
  6. import java.util.List;

  7. public class MyDataSource {
  8.     
  9.     private static String url="jdbc:mysql://localhost:3306/jdbc";
  10.     private static String user="root";
  11.     private static String password="admin";
  12.     private static int initCount=5;
  13.     private static int maxCount=10;
  14.     private int currentCount=0;
  15.     private LinkedList<Connection> connectionsPool=new LinkedList<Connection>();
  16.     
  17.     public MyDataSource(){
  18.         for(int i=0;i<initCount;i++){
  19.              try {
  20.                  //先入先出的算法
  21.                 this.connectionsPool.addLast(this.createConnection());
  22.                 this.currentCount++;
  23.             } catch (SQLException e) {
  24.                 throw new ExceptionInInitializerError(e);
  25.             }
  26.         }
  27.     }
  28.     
  29.      public Connection getConnection() throws SQLException{
  30.          synchronized(connectionsPool){
  31.              if(connectionsPool.size()>0)
  32.              return this.connectionsPool.removeFirst();
  33.              if(this.currentCount<maxCount){
  34.                  this.currentCount++;
  35.                  return this.createConnection();
  36.              }
  37.             throw new SQLException("已没有连接!");
  38.          }
  39.      }
  40.      private Connection createConnection() throws SQLException{
  41.          return DriverManager.getConnection(url, user, password);
  42.      }
  43.     
  44.      public void free(Connection conn){
  45.          this.connectionsPool.addLast(conn);
  46.      }
  47. }

多线程并发问题、并发获取连接可能会出现安全问题,需要给代码加上同步块,使其串行获取连接,即加上锁。

阅读(924) | 评论(0) | 转发(0) |
0

上一篇:JDBC性能的优化

下一篇:面向对象之抽象类

给主人留下些什么吧!~~