寫了個連線池的類,和大家一起探討,歡迎交流

dalong發表於2003-07-31
寫了個連線池的類,和大家一起探討,歡迎交流

package com.dalong.connectionpool;
import java.util.HashMap;
import java.util.Vector;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
public class ConnectionPool {
//連線池的管理器,首先初始化,僅僅有一個物件,管理連線池
private static HashMap connectionPoolManager=new HashMap();
//沒有用過的連線池,用vector實現同步
private static Vector noUseConnectionPool;
//沒有用過的連線池
private static HashMap nowUseConnectionPool;

private static String dbDriver="odbc:jdbc:OdbcJdbcDriver";
private static String dbUrl="dalong@XX";
private static String userName="dalong";
private static String userPassword="dalong";

//預設為100個連線池
private static int MAX_POOL=100;

//singleTon 設計模式
private ConnectionPool(String driver,String url,String name,String password,int max)
throws ClassNotFoundException {
Class.forName(driver);
dbUrl=url;
userName=name;
userPassword=password;
MAX_POOL=max;
}
public static ConnectionPool getConnManagerInstance(String poolName)
throws ClassNotFoundException{
ConnectionPool tempPool=(ConnectionPool)connectionPoolManager.get(poolName);
if(tempPool==null){
tempPool=new ConnectionPool(dbDriver,dbUrl,userName,userPassword,MAX_POOL);
connectionPoolManager.put(poolName,tempPool);
return tempPool;
}else
return tempPool;
}
//透過連線池獲得真正的連結
public static Connection getConnection() throws java.sql.SQLException{
Connection conn=null;
synchronized(noUseConnectionPool){
if(noUseConnectionPool.size()>0){
conn=(Connection)noUseConnectionPool.firstElement();
noUseConnectionPool.remove(conn);
return conn;
}
}
//如果資料庫連線池沒有連結了,自己建立一個
if(conn==null){
conn=createConnection(dbDriver,dbUrl,userName,userPassword);
}else if(conn.isClosed()){
nowUseConnectionPool.remove(conn);
conn=createConnection(dbDriver,dbUrl,userName,userPassword);
}
conn.setAutoCommit(false);
nowUseConnectionPool.put(conn,conn);
return conn;
}
//如果連線池沒有連結了,就需要產生一個連結
private static Connection createConnection(String driver,String url,String user,String password)
throws java.sql.SQLException{
Connection conn=DriverManager.getConnection(url,user,password);
return conn;
}
public static void releaseConnection(Connection conn,boolean isCommit)
throws java.sql.SQLException{
if(isCommit)
conn.commit();
else
conn.rollback();
nowUseConnectionPool.remove(conn);
if(noUseConnectionPool.size() + nowUseConnectionPool.size()<MAX_POOL){
synchronized(noUseConnectionPool){
noUseConnectionPool.add(conn);
}
}else{
conn.close();
}
}
public static void main(String[] args) {
//測試模擬10個客戶
for (int i = 0; i < 10; i++) {
try {
//xxxx 一般為屬性檔案讀取
ConnectionPool pool = ConnectionPool.getConnManagerInstance("xxxx");
Connection conn = pool.getConnection();
}catch (SQLException ex1) {
//處理異常
}
catch (ClassNotFoundException ex) {
//處理異常
}
}
}
}

相關文章