Java Implements database connection pooling

Source: Internet
Author: User

 PackageNju.iip.dao;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.util.Map;ImportJava.util.Map.Entry;ImportJava.util.concurrent.ConcurrentHashMap;ImportNju.iip.util.Config;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;/*** Connection Pool class * *@authorWangqiang **/ Public classConnectionPool {Private Static FinalLogger Logger = Loggerfactory.getlogger (connectionpool.class); Private intMax_connection = integer.valueof (Config.getvalue ("max_connection"));//Maximum number of connections    Private intMin_connection = integer.valueof (Config.getvalue ("min_connection"));//minimum number of connections    PrivateMap<connection,string> Connection_map;//container that holds the connection pool    Private StaticConnectionPool Connectpool;//Single Case        Private intWaitTime = 100; PrivateConnectionPool () {Logger.info ("Create Connection pool ....");        Intializepool (); Logger.info ("Create connection Pool succeeded ...." Total "+connection_map.size () +" connections "); }    /*** Get Connection Pool Singleton * *@returnConnectpool*/     Public StaticConnectionPool getinstance () {if(Connectpool = =NULL) {            synchronized(ConnectionPool.class) {                if(Connectpool = =NULL) {Connectpool=NewConnectionPool (); }            }        }        returnConnectpool; }     Public voidIntializepool () {if(Connection_map! =NULL) {            return; } Connection_map=NewConcurrenthashmap<connection,string>(); Try {             for(inti = 0; i < min_connection; i++) {connection_map.put (GetNewConnection (),"Free"); }        } Catch(Exception e) {logger.info ("Intializepool Error", E); }    }     PublicConnection 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); }        returnConn; }    /*** Get a connection *@return     */     PublicConnection 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 ();//Create a new connectionCONNECTION_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 (); }        }        returnConn; }        /*** Release Connection *@parammyconnection*/     Public synchronized voidreleaseconnection (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 voidWaitintwaitTime) {        Try{thread.sleep (waitTime); }Catch(Exception e) {logger.info ("Wait Error", E); }    }}

Java Implements database connection pooling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.