java實現資料庫連接池

來源:互聯網
上載者:User

標籤:

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實現資料庫連接池

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.