標籤:
package nju.iip.dao;import java.sql.Connection;import java.sql.DriverManager;import java.util.Map;import java.util.Map.Entry;import java.util.concurrent.ConcurrentHashMap;import nju.iip.util.Config;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * 串連池類 * * @author wangqiang * */public class ConnectionPool { private static final Logger logger = LoggerFactory.getLogger(ConnectionPool.class); private int max_connection = Integer.valueOf(Config.getValue("max_connection"));// 最大串連數 private int min_connection = Integer.valueOf(Config.getValue("min_connection"));// 最小串連數 private Map<Connection,String> connection_map;// 存放串連池的容器 private static ConnectionPool connectPool;// 單例 private int waitTime = 100; private ConnectionPool() { logger.info("建立串連池...."); intializePool(); logger.info("建立串連池成功....共"+connection_map.size()+"個串連"); } /** * 擷取串連池單例 * * @return connectPool */ public static ConnectionPool getInstance() { if (connectPool == null) { synchronized (ConnectionPool.class) { if (connectPool == null) { connectPool = new ConnectionPool(); } } } return connectPool; } public void intializePool() { if (connection_map != null) { return; } connection_map = new ConcurrentHashMap<Connection,String>(); try { for (int i = 0; i < min_connection; i++) { connection_map.put(getNewConnection(),"free"); } } catch (Exception e) { logger.info("intializePool error", e); } } public Connection getNewConnection() { Connection conn = null; try { Class.forName(Config.getValue("DBDRIVER")); conn = DriverManager.getConnection(Config.getValue("DBURL"), Config.getValue("DBUSER"),Config.getValue("DBPASSWORD")); } catch (Exception e) { logger.info("getNewConnection error", e); } return conn; } /** * 擷取一個串連 * @return */ public Connection getConnection() { Connection conn = null; for (Entry<Connection, String> entry : connection_map.entrySet()) { if (entry.getValue().equals("free")) { conn = entry.getKey(); connection_map.put(conn,"busy"); break; } } if (conn == null) { if (connection_map.size() <max_connection) { conn = getNewConnection();//建立一個串連 connection_map.put(conn,"busy"); logger.info("no free connection,add new connection ok!"); } else { logger.info("reach max_connction!start watting..."); wait(waitTime); conn = getConnection(); } } return conn; } /** * 釋放串連 * @param myconnection */ public synchronized void releaseConnection(Connection conn) { if(conn == null) { return; } try{ if(connection_map.containsKey(conn)) { if(conn.isClosed()) { connection_map.remove(connectPool); } else{ connection_map.put(conn,"free"); logger.info("releaseConnection ok..."); } } else { conn.close(); } }catch(Exception e){ logger.info("releaseConnection error", e); } } public void wait(int waitTime) { try{ Thread.sleep(waitTime); }catch(Exception e){ logger.info("wait error", e); } }}
java實現資料庫連接池