A very good trial effect of the database connection pool--java

Source: Internet
Author: User
Tags connection pooling getmessage

Objective:

Although many enterprise application servers now have their own database connection pooling capabilities, even Tomcat supports this feature. However, in many cases, we still use database connection pools, such as: Java desktop applications that access the database, and so on. This database connection pool is based on the example of "Inside Servlets" in the book, after trial, the effect is very good. Special release sharing.

Source

Connectionpool.java package com.abner.dbconnector; Import java.sql.*; Import java.util.*; The/** * ConnectionPool class creates a connection pool that specifies the size of a particular database. The connection pool Object * Allows the client to specify the JDBC driver, database, using the database's user name and password. Also, * Clients can specify the number of connection pools that are created in the initial creation, and specify the number of connections that are automatically increased each time the connection is not sufficient and the maximum number of database connections connected to the pool. * * Methods available Externally: ConnectionPool: Constructor * getinitialconnections: Return connection pool Initialization size * Setinitialconnections: Set Connection pool initialization size * Getincrementa Lconnections: Returns the incremental increment of connection pool * Setincrementalconnections: Set the size of the connection pool automatically increased * Getmaxconnections: Maximum allowable number of connections for the connection pool * Setmaxconnections: Set the maximum allowable number of connections for a connection pool * gettesttable: Get the name of the test table * settesttable: Set the name of the test table * CreatePool: Create connection pool, line Cheng sync * getconn Ection: Get a database connection from the connection pool * returnconnection: Returns a connection to the connection pool * Refreshconnections: Refresh Connection Pool * Closeconnectionpool: Close Connection Pool * * @aut Hor Abnerchai Email: [email protected] * @version 1.0.0 * */public class ConnectionPool {   private Strin G jdbcdriver = ""; Database driver    Private String dburl = ""; Data URL    private String dbusername = ""; Database user name    privateString Dbpassword = ""; Database user password    private String testtable = ""; Test table name that tests whether the connection is available, default no test table    private int initialconnections = 10; Initial size of connection pool    private int incrementalconnections = 5;//Connection Pool auto-increment size    private int maxconnections = 50 ; Maximum size of connection pool    private Vector connections = null; The vector that holds the database connection in the connection pool, initially null//It holds an object of type Pooledconnection/** * constructor * * @param jdbcdriver string JDBC driver String * @param db URL string Database URL * @param dbusername string Connection database user name * @param dbpassword string Connection database user's password * */public ConnectionPool (St Ring jdbcdriver,string dburl,string dbusername,string dbpassword) {   this.jdbcdriver = jdbcdriver;  & nbsp This.dburl = Dburl;    this.dbusername = dbusername;    This.dbpassword = Dbpassword; /** * Returns the initial size of the connection pool * * @return number of connections available in the initial connection pool */public int getinitialconnections () {   return this.initialconn ections; /** * Set Initial size of connection pool * * @param to set the number of connections in the initial connection pool */public VOID setinitialconnections (int initialconnections) {   this.initialconnections = initialconnections;}/** * return The connection pool automatically increases in size, * * @return Connection pool automatically increases in size */public int getincrementalconnections () {   return This.incrementalconnec tions; /** * Set the connection pool automatically increased size * @param the size of the connection pool automatically increases */public void setincrementalconnections (int incrementalconnections) { &nbs P This.incrementalconnections = incrementalconnections; /** * Returns the maximum number of available connections in the connection pool * @return Maximum number of connections available in the connection pool */public int getmaxconnections () {   return this.maxconnection S /** * Set the maximum number of connections available in the connection pool * * @param set the maximum number of connections available in the connection pool */public void setmaxconnections (int maxconnections) {   th Is.maxconnections = MaxConnections; }/** * Gets the name of the test database table * * @return Test database table name */public String gettesttable () {   return this.testtable;}/** * Settings The name of the test table * @param testtable string Test table name */public void settesttable (String testtable) {   this.testtable = Test Table; /** * * Create a database connection pool with the number of available connections in the connection pool in the classThe value set in Initialconnections */public synchronized void CreatePool () throws Exception {//Ensure that the connection pool is not created//If the connection pool has already been created, save the connected The amount connections will not be empty if (connections! = null) {    return;//If it has been created, return}//Instantiate the driver class instance specified in the JDBC Driver driv ER driver = (driver) (Class.forName (This.jdbcdriver). newinstance ()); Drivermanager.registerdriver (driver); Register the JDBC driver//Create a vector to save the connection, initially with 0 elements connections = new vector (); Create a connection based on the value set in Initialconnections. Createconnections (this.initialconnections);     System.out.println ("Database connection pool creation succeeded! "); } /** * Create a specified number of database connections by numconnections and put these connections * into the connections vector * * @param numconnections the number of database connections to create */private void C  reateconnections (int numconnections) throws SQLException {//loops create a specified number of database connections for (int x = 0; x < numconnections; + +) { Has the number of database connections in the connection pool been maximized? The maximum value is indicated by the class member MaxConnections//, if MaxConnections is 0 or negative, there is no limit to the number of connections. If the number of connections has reached its maximum, exit.    if (this.maxconnections > 0 && this.connections.size () >= this.maxconnections) {      break,   }//add a new Pooledconnection object to Conne Ctions vector//Add a connection to the connection pool (in Vector connections) try{    connections.addelement (New Pooledconnection ( Newconnection ())); }catch (SQLException e) {    System.out.println ("Failed to create database connection! "+e.getmessage ());     throw new SQLException (); }     System.out.println ("Database connection created ...");} /** * Create a new database connection and return it * * @return return a newly created database connection */private Connection newconnection () throws SQLException {//Create a database connection C Onnection conn = drivermanager.getconnection (Dburl, Dbusername, Dbpassword); If this is the first time a database connection is created, that is, the database is checked for the number of//maximum client connections allowed for this database//connections.size () ==0 indicates that there is currently no connection created if (connections.size () = = 0) {&nbs p;  DatabaseMetaData metaData = Conn.getmetadata ();    int drivermaxconnections = Metadata.getmaxconnections (); The drivermaxconnections returned by the database is 0, indicating that the database does not have a maximum//connection limit, or that the maximum connection limit for the database is not known//drivermaxconnections is a returned integer that indicates the number of client connections that this database allows//if the maximum number of connections set in the connection pool is greater than the number of connections allowed for the database, the maximum number of connections to the database is the maximum//connection number allowed for the databases     if ( Drivermaxconnections > 0 && this.maxconnections > drivermaxconnections) {      This.maxconnections = drivermaxconnections;    }} return conn; Returns the new database connection created}/** * Returns an available database connection by calling the Getfreeconnection () function, * If no database connection is currently available and more database connections cannot be built (such as a limit on connection pool size), this function waits for a moment to try again Get. * * @return Returns an available database connection object */public synchronized Connection getconnection () throws SQLException {//Make sure the connection Chi is created if (Connec tions = = null) {    return null;//connection pool not created, return null} Connection conn = Getfreeconnection (); Get an available database connection//If there is currently no connection available, that is, all connections are in use while (conn = = null) {//Wait a second to retry     wait;   &nbs P conn = Getfreeconnection (); Retry until the available connection is obtained, if//getfreeconnection () returns null//indicates that a batch of connections is not available after the connection is created} return conn;//the available connections obtained}/** * This function from the connection pool vector An available database connection is returned in connections, and if * There is currently no database connection available, this function is based on IncremEntalconnections sets the value of the * to create several database connections and put them into the connection pool. * If all connections are still in use after creation, returns NULL * @return returns an available database connection */private Connection getfreeconnection () throws SQLException {//From connection Get an available database connection in the pool Connection conn = Findfreeconnection (); if (conn = = null) {//If there are no connections available in the current connection pool//create some connections createconnections (incrementalconnections);//re-find available connections from the pool conn = findf Reeconnection (); if (conn = = null) {//returns NULL    return NULL if the connection is still not available after the link is created;}} Return conn; /** * Find all connections in the connection pool, find an available database connection, * If no connection is available, returns NULL * * @return Returns an available database connection */private Connection findfreeconnection () Throws SQLException {Connection conn = null; Pooledconnection pconn = null; Get all the objects in the connection pool vector enumeration en = connections.elements (); Iterate through all the objects to see if there are any available connections while (En.hasmoreelements ()) {   Pconn = (pooledconnection) en.nextelement ();  & nbsp if (!pconn.isbusy ()) {   //If this object is not busy, obtain its database connection and set it to busy     conn = Pconn.getconnection (); nbsp;   Pconn.setbusy (TRUE);    //Test If this connection is available     if (!testconnection (conn)) {    //If this connection is no longer usable, create a new connection ,     //And replace this unavailable connection object, if creation fails, returns null      try{        conn = Newconnection ();     }catch (SQLException e) {       System.out.println (" Failed to create DATABASE connection! "+e.getmessage ());        return null;     }       pconn.setconnection (conn);   }    break; Have found an available connection, exit}} return conn;//returns the available connections found to/** * Test if a connection is available, if it is not available, turn it off and return false * Otherwise available return true * * @param conn The number of tests required According to the library connection * @return return TRUE indicates that this connection is available, false indicates not available */private Boolean testconnection (Connection conn) {try {  // Frequently exists    if (Testtable.equals ("")) {    //If the test table is empty, try using the Setautocommit () method of this connection  & nbsp;  //To determine if the connection is available (this method is available only in some databases, if not available,     //throws an exception). Note: The method of using the test table is more reliable      conn.setautocommit (true);   } else {//test table test with test tables tested     //check If this connection is valid    &nbs P Statement stmt = Conn.createstatement ();      Stmt.execute ("SELECT count (*) from" + TestTable);}} catch (SQLException e) {//throws an exception above, this connection is not available, closes it and returns false; CloseConnection (conn); return false;}//Connection available, return true return TR Ue }/** * This function returns a database connected to the connection pool, and the connection is set to idle. * All database connections obtained using connection pooling should be returned when this connection is not used. * * @param the Connection object to be returned to the connection pool */public void returnconnection (Connection conn) {//Make sure the connection pool exists, if the connection is not created (not present), return directly if (connections = = null) {System.out.println ("Connection pool does not exist, cannot return this connection to the connection pool!"); return;} Pooledconnection pconn = null; Enumeration en = Connections.elements (); Traverse all connections in the connection pool to find the connection object to return while (En.hasmoreelements ()) {Pconn = (pooledconnection) en.nextelement (); Find the Connection object to return in the connection pool first if (conn = = Pconn.getconnection ()) {//found, set this connection as idle state pconn.setbusy (FALSE); }}}/** * Refreshes all connection objects in the connection pool * */public synchronized void Refreshconnections () throws SQLException {//Ensure that the connection pool has been innovated if (conn Ections = = null) {System.out.println ("Connection pool does not exist, cannot be refreshed!"); return;} Pooledconnection pconn = null; Enumeration en = Connections.elements (); while (En.hasmoreelements ()) {//Gets a Connection object pconn = (pooledconnection) en.nextelement ();//If the object is busy, wait 5 seconds, and then refresh the if (Pconn) directly after 5 seconds . IsBusy ()) {Wait (5000);//wait 5 seconds}//Close this connection and replace it with a new connection. CloseConnection (Pconn.getconnection ()); Pconn.setconnection (Newconnection ()); Pconn.setbusy (FALSE); }}/** * Closes all connections in the connection pool and empties the connection pool. */Public synchronized void Closeconnectionpool () throws SQLException {//Ensure connection pool exists, if not present, return if (connections = null) {&NB sp;  System.out.println ("Connection pool does not exist, cannot be closed!");    return; } pooledconnection pconn = null; Enumeration en = Connections.elements (); while (En.hasmoreelements ()) {   Pconn = (pooledconnection) en.nextelement ();//If Busy, wait 5 seconds    if (pCo Nn.isbusy ()) {    &nbsP Wait (5000); Wait 5 Seconds    }//5 seconds to close it directly closeconnection (Pconn.getconnection ()); Remove it from the connection pool vector connections.removeelement (pconn); }//The connection pool is empty connections = NULL; /** * Close a database connection * * @param need to close the database connection */private void CloseConnection (Connection conn) {try {conn.close ();} catch (SQLException e) {System.out.println ("failed to close database connection:" +e.getmessage ());}} /** * Causes the program to wait for a given number of milliseconds * * @param given number of milliseconds * * private void Wait (int mseconds) {try {thread.sleep (mseconds);} catch (Interrupte Dexception e) {}}/** * * The class used internally to hold connection objects in the connection pool * There are two members in this class, one is the database connection and the other is the flag that indicates whether this connection is in use. */class Pooledconnection {   Connection Connection = null;//database connection    Boolean busy = false;//Is this connection The flag being used, default is not using the   //constructor, according to a Connection to construct a Pooledconnection object    public pooledconnection ( Connection Connection) {     this.connection = Connection;    }     Returns the connection     public Connection in this object Getconnection () {      return connection;    }//Set this object, connection public void SetConnection (Co Nnection connection) {   this.connection = connection;}//Get object connected whether busy public boolean isBusy () {   re Turn busy; }//Setting the connection of the object is busy public void Setbusy (Boolean busy) {   this.busy = busy;}} I have written all the explanations of this program in detail in the source program, I think it is not necessary to explain more.

If you have improved or modified, please keep the original author's statement

A very good trial effect of the database connection pool--java

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.