主题:Tomcat连接池原理讨论
文章来源:365jz.com 点击数:
297 更新时间:2009-09-18 10:23
参与评论
- 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();;
-
- 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";
-
-
- private static int MAX_POOL=100;
-
-
- 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); {
-
- for (int i = 0; i < 10; i++); {
- try {
-
- ConnectionPool pool = ConnectionPool.getConnManagerInstance("xxxx");;
- Connection conn = pool.getConnection();;
-
- }catch (SQLException ex1); {
-
- }
- catch (ClassNotFoundException ex); {
-
- }
- }
- }
- }
如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛
------分隔线----------------------------