A database connecting pool with very good effect
Foreword: Although many enterprise-class application servers have their own database connection pool features, even Tomcat also supports this feature. However, in many times, we still have to use the database connection pool, such as the Java desktop application that access the database, etc. This database connection pool is the renovation of the example in the "Inside Servlets" book, after the trial, the effect is very good. Special cloth sharing. (Author: abnerchai contact me: josserchai@yahoo.com) source code //ConnectionPool.java package com.abner.dbconnector; import java.sql *; import java.util *; / ** * ConnectionPool class creates a. Specify the size of the connection pool for a particular database. Connection pool object * Allows the client to specify a JDBC driver, database, username and password using the database. Moreover, * Client can specify the connection pool at the initial creation of the database to generate the number of database connections, and specify the number of database connections to the number of connected connections each time when the connection * is not sufficient.
* * External methods: ConnectionPool: Constructor: Connected Pool Initialization Size * SETINITILALCONNECTIONS: Settings Connection Pool Initial Size * GetIncrementalConnections: Return Connection Pool Auto Added Increase * SETINCREMENTALCONNECTIONS: Settings the Size of the connection pool * * GetMaxConnections: Get the maximum allowable connection of the connection pool * SetMaxConnections: Set the maximum allowable connection of the connection pool * GetTestTable: Get the name of the test table * settesttable: Set the name of the test table * CreatePool: Create a connection pool, thread Synchronization * getConnection: Get a database connection from the connection pool * ReturnConnection: Return to a connection to the connection pool * Refreshconnections: refresh connection pool * CloseConnectionPool: Close connection pool * * @Author Abnerchai email: josserchai@yahoo.com * @version 1.0.0 * * / public class connectionpool {private string jdbcdriver = ""; // Database driver private string dburl = ""; // data url private string dbusername = "; // database username private string dbpassword =" " ; // Database User Password Private String TestTable = ""; // Test whether the connection is available to the test table name, the default does not test table private int initialconnections = 10; // Connect the pool initial size private int incretribonnections = 5; // connection Automatic Size Private Int MaxConnections = 50; // Connecting Pool Max Size Private Vector Connections = NULL; / / Store the vector in the connection pool, the initial time is null // The object stored in it is the pooledConnection type / ** * constructor * * @Param JDBCDRIVER STRING JDBC drive class string * @Param DBURL STRING Database URL * @Param dbUsername String connection database username * @param dbPassword String connection database user password * * / public ConnectionPool (String jdbcDriver, String dbUrl, String dbUsername, String dbPassword) {this.jdbcDriver = jdbcDriver; this.dbUrl = dbUrl; this.dbUsername = DBUSERNAME; this.dbpassword = dbpassword;} / ** * Returns the initial size of the connection pool * * @returN the number of connections available in the initial connection * / public int GetInitialConnections () {Return this.initialConnections;
} / ** * Setting the initial size of the connection pool * * @Param Used to set the number of connections in the initial connection pool * / public void setinitialconnections (int initialconnections) {this.initialconnections = initialconnections;} / ** * Return the connection pool automatic Increased size, * @returN connection pool automatically adds size * / public int getincrementalconnections () {return this.incrementalconnections;} / ** * Settings the connection pool automatically increases * @Param connection pool automatically increases size * / public void setIncrementalConnections (int incrementalConnections) {this.incrementalConnections = incrementalConnections;} / ** * returns the connection pool * maximum available number of connections the maximum number of available connections in the connection pool @return * / public int getMaxConnections () {return this. MaxConnections;} / ** * Set the maximum number of connections in the connection pool * * @Param Set the maximum number of connections in the connection pool * / public void setMaxConnections (int maxConnections) {this.maxconnections = maxconnections;} / ** * Get the name of the test database table * * @Return test database table name * / public string gettesttable () {return this.testtable;} / ** * Set the name of the test table * @Param TestTable String Test Table Name * / Public void settesttable (string testtable) {this.testtable = TestTable;} / ** * * Create a number According to the library connection pool, the number of available connections in the connection pool is used to set the value set in INITIALCONNECTIONS * / public synchronized void createPool () throws exception {// Make sure the connection pool is not created // If the connection pool is created, Save Connected Vector Connections will not be empty if (Connections! = NULL) {return; // If you have been created, return} // Instance Driver DRiver DRiver = (DRIVER) specified in JDBC DRIVER (Class). Forname (this.jdbcdriver); DRIVERMANAGER.REGISTERDRIVER (DRIVER); // Registering a JDBC driver // Create a saved vector, there are 0 elements for 0 elements = new vector (); // According to InitialConnections The value set is created.
CreateConnections; System.out.Println ("Database Connection Pool Creation!");} / ** * Create a database connection specified by NumConnections, and put these connections * in the Connections vector * * @ @ @@@ PARAM NUMCONNECTIONS Number of database connections To create * / Private Void CreateConnections (int NumConnections) THROWS SQLEXCEPTION {// Create a specified number of database connection for (int x = 0; x IF (this.maxConnections> 0 && this.connections.size ()> = this.maxconnections) {Break;} // add a new pooledconnection object to connection connections vector // Add a connection to the connection pool (vector Connections) Try {Connections.addelement (New PooledConnection);} catch (SQLEXCEPTION E) {system.out.println ("Create a database connection failed!" E.getMessage ()); throw new sqlexception ();} system .out.println ("Database Connection Create ...");}} / ** * Create a new database connection and return it * * @return Return to a newly created database connection * / private connection newconnection () THROWS SQLEXCEPTION {// Create a database connection connection conn = driverManager.getConnection (DBURL, DBUSERNAME, DBPASSWORD); // If this is the first time you create a database connection, that is, check the database, get this database allowed to support // maximum Customer connection Number //Connections.size()==0 indicates that there is no connection to be created if it is created (Connections.Size () == 0) {DatabaseMetadata metadata = conn.getMetadata (); int DrivermaxConnections = metadata.getmaxconnections () // DRIVERMAXCONNECTIONS returned by the database is 0, indicating that this database does not have the maximum // connection limit, or the maximum connection limit for the database does not know the // DRIVERMAXCONNECTIONS is an integer returned, indicating that this database allows the number of clients to connect // If connecting pool The maximum number of connections set is greater than the number of connections allowed by the database. Set the maximum // of the connection pool to the maximum number of numbers allowed by the database (DriverMaxConnections> 0 && this.maxConnections> DrivermaxConnections) {this.maxconnections = drivermaxconnections;}} returnconnections; // Return to created new database connection} / ** * Returns a available database connection by calling the getFreeConnection () function, * If there is no database connection available, more database connections cannot be created (such as the limit of the connection pool size), this function is waiting for a while Try it again. * * @return Returns an available database connection object * / public synchronized connection getConnection () throws sqlexception {// Make sure the connection pool is created if (Connections == null) {return null; // The connection pool has not been created, then Returns NULL} Connection Conn = getFreeConnection (); // Get a available database connection // If there is no connection available, all the connections are used in use, while (conn == null) {// wait for a while Try WAIT (250); conn = getfreeConnection (); // Re-try until you get available connections, if // getFreeConnection () returns null // indicates that you can not get available connection after creating a batch of connections} Return Conn; // Returns the available connection} / ** * This function returns an available database connection from the connection pool vector Connections, if * currently no available database connection, this function is created according to the value of IncrementalConnections setting * Several database connections and put them in the connection pool. * If you are created, all connections are still in use, then return null * @return Returns a available database connection * / private connection getfreeConnection () THROWS SQLEXCEPTION {// get a available database connection CONNECTION CONN = FindFreeConnection (); if (conn == null) {// If there is no connection // created in the current connection pool to create some connection CreateConnections (INCREMENTALCONNECTIONS); // Find from the pool to access the connection conn = FindFreeConnection () ; if (conn == null) {// If there is no available connection after the connection is created, return null return null;}} return conn;} / ** * Find all connections in the connection pool, find an available Database connection, * If there is no connection available, return null * * @return returns an available database connection * / private connection findfreeConnection () throws SQLEXCEPTION {Connection conn = null; PooledConnection PConn = NULL; // Get the connection pool vector All objects enumeration enum = connections.ersion (); // Traverse all objects to see if there is available connection while (enum.hasmoreElements ()) {PConn = (PooledConnection) enum.nexTelement (); if (! Pconn. ISBUSY ()) {// If this object is not busy, get its database connection and set it to busy conn = pConn.getConnection (); PConn.setbusy (TRUE); // Test if this connection can be used if (! TestConnection (conn)) {// If this connection is not available, create a new connection, // and replace this unavailable connection object, if you create a failure, return null try {conn = newconnection ();} catch (sqlexception e) {system.out.println ("Create a database connection failed! " E.GetMessage ()); Return Null;} PConn.setConnection (CONN);} Break; // Self-found an available connection, exit}} return conn; // Return to find available connection} / * * * Test if a connection is available, if you are not available, turn off it and return false * Otherwise, return true * * @Param CONN Requires Database connection * @return Returns true indicates that this connection is available, false means unavailable * / private Boolean TestConnection (Connection Conn) {// Judging whether the test table exists if (TestTable.equals ("))) {// If the test table is empty, try to use the setAutocommit () method // to determine the connection Noisy (this method is only available in some databases, If not available, // throw an exception). Note: The method of using the test form is more reliable for conn.setautocommit (TRUE);} Else {// Test Table Test // Check if this connection is valid statement stmt = conn.createment (); stmt.execute ("SELECT Count (*) from" TestTable);}} Catch (SQLException E) {// Throw an exception, this connection is unavailable, close it, and return false; closeConnection (conn); returnaf / / Connection is available, return True Return True;} / ** * This function returns a database to connect to the connection pool and set this connection to idle. * All database connections available to the connection pool should be returned when not using this connection. * * @PARAM You need to return to the connection object in the connection pool * / public void returnConnection (Connection Conn) {// Make sure the connection pool exists, if the connection is not created (not existent), return if (Connections == null) {system .out.println ("connection pool does not exist, can not return this connection to the connection pool!"); return;} PooledConnection PConn = null; Enumection enum = connection = connection = connection = connection = connection = connection, Find this connection object while (Enum.hasMoreElements ()) {PConn = (PooledConnection) ENUM.NEXTELEMENT (); // First find the connection object IF to return in the connection pool (conn == pconn.getConnection) ) {// found, set this connection as idle status PConn.setbusy (false); break;}}} / ** * Refresh Connection Pool All connection objects * * / public synchronized void refreshconnections () THROWS SQLEXCEPTION {/ / Make sure the connection pool has an innovation of IF (connections == null) {system.out.println ("Connection pool does not exist, unable to refresh!"); Return;} PooledConnection PConn = null; enumeration enum = connection. While (Enum.hasMoreElements ()) {// Get a connection object PConn = (PooledConnection) enum.nexTelement (); // If the object is busy with 5 seconds, 5 seconds directly refresh the IF (PConn.isbusy ()) { Wait (5000); // Wait 5 second} // Turns this connection, replaced it with a new connection. CloseConnection (PConn.getConnection ()); PConn.setConnection (NewConnection ()); PConn.setBusy (false);}} / ** * Close all connections in the connection pool and clear the pool.