Import java. SQL. connection;
Import java. SQL. databasemetadata;
Import java. SQL. driver;
Import java. SQL. drivermanager;
Import java. SQL. sqlexception;
Import java. SQL. statement;
Import java. util. enumeration;
Import java. util. vector;
/* Although Apache commons DBCP can be used to easily establish a database connection pool,
However, as this article writes the Internal principles of the database connection pool so thoroughly and looks at the completeness,
It is really rare for developers to have a deeper understanding of the database connection pool.
Thank you for the author of this article. */
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 = ""; // name of the test table used to test whether the connection is available. No test table is available by default.
Private int initialconnections = 10; // initial size of the Connection Pool
Private int incrementalconnections = 5; // automatically increases the size of the connection pool.
Private int maxconnections = 50; // maximum size of the Connection Pool
Private vector connections = NULL; // stores the database connection vector in the connection pool. The initial value is null.
// The objects stored in it are of the pooledconnection type.
/**
* Constructor
*
* @ Param jdbcdriver string JDBC Driver Class string
* @ Param dburl string Database URL
* @ Param dbusername string Connection database username
* @ Param dbpassword string password used to connect to the database
*
*/
Public connectionpool (string jdbcdriver, string dburl, string dbusername,
String dbpassword ){
This. jdbcdriver = jdbcdriver;
This. dburl = dburl;
This. dbusername = dbusername;
This. dbpassword = dbpassword;
Try {
Createpool ();
} Catch (exception e ){
E. printstacktrace ();
}
}
/**
* Returns the initial size of the connection pool.
*
* @ Return the number of connections available in the initial connection pool
*/
Public int getinitialconnections (){
Return this. initialconnections;
}
/**
* Set the initial size of the connection pool.
*
* @ Param is used to set the number of connections in the initial connection pool.
*/
Public void setinitialconnections (INT initialconnections ){
This. initialconnections = initialconnections;
}
/**
* Returns the size,
*
* @ Return the automatically increased size of the Connection Pool
*/
Public int getincrementalconnections (){
Return this. incrementalconnections;
}
/**
* Set the Automatically increasing size of the connection pool.
* @ Param the size automatically added by the connection pool
*/
Public void setincrementalconnections (INT incrementalconnections ){
This. incrementalconnections = incrementalconnections;
}
/**
* Returns the maximum number of available connections in the connection pool.
* @ Return the maximum number of available connections in the connection pool
*/
Public int getmaxconnections (){
Return this. maxconnections;
}
/**
* Set the maximum number of available connections in the connection pool.
*
* @ Param: sets the maximum number of available connections in the connection pool.
*/
Public void setmaxconnections (INT maxconnections ){
This. maxconnections = maxconnections;
}
/**
* Obtain the name of the test database table
*
* @ Return name of the test database table
*/
Public String gettesttable (){
Return this. testtable;
}
/**
* Set the name of the test table.
* @ Param testtable string name of the test table
*/
Public void settesttable (string testtable ){
This. testtable = testtable;
}
/**
*
* Create a database connection pool. The number of available connections in the connection pool is composed of class members.
* Value set in initialconnections
*/
Public synchronized void createpool () throws exception {
// Make sure the connection pool is not created
// If the connection pool has been created, the connections vector for saving the connection will not be empty.
If (connections! = NULL ){
Return; // if it has been created, return
}
// Instantiate the specified driver class instance in the JDBC driver
Driver driver = (driver) (class. forname (this. jdbcdriver). newinstance ());
Drivermanager. registerdriver (driver); // register the JDBC driver
// Create a vector for saving the connection. At first, there are 0 elements.
Connections = new vector ();
// Create a connection based on the value set in initialconnections.
Createconnections (this. initialconnections );
System. Out. println ("database connection pool created successfully! ");
}
/**
* Create a database connection specified by numconnections and set these connections
* Put in the connections Vector
*
* @ Param numconnections: number of database connections to be created
*/
Private void createconnections (INT numconnections) throws sqlexception {
// Create a specified number of database connections cyclically
For (INT x = 0; x <numconnections; X ++ ){
// Has the maximum number of database connections in the connection pool reached? Maxcompute
// Indicates that if maxconnections is 0 or negative, there is no limit on the number of connections.
// Exit if the number of connections reaches the maximum.
If (this. maxconnections> 0
& This. Connections. Size ()> = This. maxconnections ){
Break;
}
// Add a new pooledconnection object to connections Vector
// Add a connection pool (in vector connections)
Try {
Connections. addelement (New pooledconnection (newconnection ()));
} Catch (sqlexception e ){
System. Out. println ("An error occurred while creating the database connection! "+ E. getmessage ());
Throw new sqlexception ();
}
System. Out. println ("the database connection has been created ......");
}
}
/**
* Create a new database connection and return it
*
* @ Return returns 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 a database connection is created, check the database and obtain the supported
// Maximum number of customer connections
// Connections. Size () = 0 indicates that no connection has been created.
If (connections. Size () = 0 ){
Databasemetadata metadata = conn. getmetadata ();
Int drivermaxconnections = metadata. getmaxconnections ();
// If the value of drivermaxconnections returned by the database is 0, the database does not have the maximum value.
// The connection limit, or the maximum connection limit of the database is unknown
// Drivermaxconnections is an integer returned, indicating the number of connections allowed by the database.
// If the maximum number of connections set in the connection pool is greater than the number of connections allowed by the database, set the maximum number of connections in the connection pool.
// The maximum number of connections allowed by the database
If (drivermaxconnections> 0
& This. maxconnections> drivermaxconnections ){
This. maxconnections = drivermaxconnections;
}
}
Return conn; // return the new database connection.
}
/**
* Call the getfreeconnection () function to return an available database connection,
* If no available database connection exists, and more database connections cannot be created
* Creation (such as the size limit of the Connection Pool). This function will be available later.
*
* @ Return returns an available database connection object.
*/
Public synchronized connection getconnection () throws sqlexception {
// Make sure the connection pool has been created
If (connections = NULL ){
Return NULL; // if the connection pool has not been created, null is returned.
}
Connection conn = getfreeconnection (); // obtain an available database connection
// If no connection is available, all connections are in use.
While (conn = NULL ){
// Wait for a while and try again
Wait (250 );
Conn = getfreeconnection (); // try again until available connections are obtained. If
// Getfreeconnection () returns NULL
// It indicates that no available connections can be obtained after a batch of connections are created.
}
Return conn; // return the available connections.
}
/**
* This function returns an available database connection from the connection pool vector connections. If
* No available database connection is currently available. This function is set according to incrementalconnections.
* Creates several database connections and puts them in the connection pool.
* If all connections are still in use after creation, null is returned.
* @ Return returns an available database connection.
*/
Private connection getfreeconnection () throws sqlexception {
// Obtain an available database connection from the connection pool
Connection conn = findfreeconnection ();
If (conn = NULL ){
// If no connection is available in the current connection pool
// Create some connections
Createconnections (incrementalconnections );
// Re-query available connections from the pool
Conn = findfreeconnection ();
If (conn = NULL ){
// If no available connection is available after the connection is created, null is returned.
Return NULL;
}
}
Return conn;
}
/**
* Search for all connections in the connection pool and an available database connection,
* If no connection is available, null is returned.
*
* @ Return returns an available database connection.
*/
Private connection findfreeconnection () throws sqlexception {
Connection conn = NULL;
Pooledconnection pconn = NULL;
// Obtain all objects in the connection pool Vector
Enumeration enumerate = connections. Elements ();
// Traverse all objects to see if there are available connections
While (enumerate. hasmoreelements ()){
Pconn = (pooledconnection) enumerate. nextelement ();
If (! Pconn. isbusy ()){
// If this object is not busy, obtain its database connection and set it to busy
Conn = pconn. getconnection ();
Pconn. setbusy (true );
// Test whether the connection is available
If (! Testconnection (conn )){
// If the connection is unavailable, a new connection is created,
// Replace the unavailable connection object. If creation fails, null is returned.
Try {
Conn = newconnection ();
} Catch (sqlexception e ){
System. Out. println ("An error occurred while creating the database connection! "+ E. getmessage ());
Return NULL;
}
Pconn. setconnection (conn );
}
Break; // you have found an available connection and exited.
}
}
Return conn; // return the available connections found
}
/**
* Test whether a connection is available. If not, disable it and return false.
* Otherwise, true is returned.
*
* @ Param conn the database connection to be tested
* @ Return true indicates that the connection is available, and false indicates that the connection is unavailable.
*/
Private Boolean testconnection (connection conn ){
Try {
// Determine whether the test table exists
If (testtable. Equals ("")){
// If the test table is empty, try using the setautocommit () method of this connection.
// To determine whether the connection is available (this method is only available in some databases, if not available,
// Throw an exception ). Note: The test table method is more reliable.
Conn. setautocommit (true );
} Else {// use the test table for testing when there is a test table
// Check if this connection is valid
Statement stmt = conn. createstatement ();
Stmt.exe cute ("select count (*) from" + testtable );
}
} Catch (sqlexception e ){
// The above throws an exception. The connection is unavailable. Close it and return false;
Closeconnection (conn );
Return false;
}
// If the connection is available, true is returned.
Return true;
}
/**
* This function returns a database connected to the connection pool and sets this connection to idle.
* All database connections obtained using the connection pool should be returned if this connection is not used.
*
* @ Param: return the connection object in the connection pool.
*/
Public void returnconnection (connection conn ){
// Ensure that the connection pool exists. If the connection is not created (it does not exist), return directly
If (connections = NULL ){
System. Out. println ("the connection pool does not exist. This connection pool cannot be returned! ");
Return;
}
Pooledconnection pconn = NULL;
Enumeration enumerate = connections. Elements ();
// Traverse all connections in the connection pool and find the connection object to return
While (enumerate. hasmoreelements ()){
Pconn = (pooledconnection) enumerate. nextelement ();
// First find the connection object to be returned in the connection pool
If (conn = pconn. getconnection ()){
// Found. Set the connection to idle.
Pconn. setbusy (false );
Break;
}
}
}
/**
* Refresh all connection objects in the connection pool.
*
*/
Public synchronized void refreshconnections () throws sqlexception {
// Ensure the connection pool has been innovated
If (connections = NULL ){
System. Out. println ("the connection pool does not exist and cannot be refreshed! ");
Return;
}
Pooledconnection pconn = NULL;
Enumeration enumerate = connections. Elements ();
While (enumerate. hasmoreelements ()){
// Obtain a connection object
Pconn = (pooledconnection) enumerate. nextelement ();
// If the object is busy, wait for 5 seconds and refresh the object after 5 seconds.
If (pconn. isbusy ()){
Wait (5000); // wait for 5 seconds
}
// Close the connection and replace it with a new connection.
Closeconnection (pconn. getconnection ());
Pconn. setconnection (newconnection ());
Pconn. setbusy (false );
}
}
/**
* Close all connections in the connection pool and clear the connection pool.
*/
Public synchronized void closeconnectionpool () throws sqlexception {
// Make sure the connection pool exists. If not, return
If (connections = NULL ){
System. Out. println ("the connection pool does not exist and cannot be closed! ");
Return;
}
Pooledconnection pconn = NULL;
Enumeration enumerate = connections. Elements ();
While (enumerate. hasmoreelements ()){
Pconn = (pooledconnection) enumerate. nextelement ();
// Wait for 5 seconds if you are busy
If (pconn. isbusy ()){
Wait (5000); // wait for 5 seconds
}
// Close it in 5 seconds
Closeconnection (pconn. getconnection ());
// Delete it from the connection pool Vector
Connections. removeelement (pconn );
}
// Leave the connection pool empty
Connections = NULL;
}
/**
* Close a database connection
*
* @ Param: database connection to be closed
*/
Private void closeconnection (connection conn ){
Try {
Conn. Close ();
} Catch (sqlexception e ){
System. Out. println ("An error occurred while closing the database connection:" + E. getmessage ());
}
}
/**
* Wait for the given number of milliseconds for the program
*
* @ Param the specified number of milliseconds
*/
Private void wait (INT mseconds ){
Try {
Thread. Sleep (mseconds );
} Catch (interruptedexception e ){
}
}
/**
* Classes used internally to save connection objects in the connection pool
* There are two members in this class. One is the database connection, and the other is to indicate whether the connection is
* The flag in use.
*/
Class pooledconnection {
Connection connection = NULL; // database connection
Boolean busy = false; // indicates whether the connection is in use. It is not in use by default.
// Constructor. A pooledconnection object is created based on a connection.
Public pooledconnection (connection ){
This. Connection = connection;
}
// Return the connection in this object
Public connection getconnection (){
Return connection;
}
// Set the connection of this object
Public void setconnection (connection ){
This. Connection = connection;
}
// Obtain whether the object connection is busy
Public Boolean isbusy (){
Return busy;
}
// Set the object connection busy
Public void setbusy (Boolean busy ){
This. Busy = busy;
}
}
}
/* ===================================================== =
This example is based on the PostgreSQL database,
Adjust the database according to the actual usage.
The call method is as follows:
① Connectionpool connpool
= New connectionpool ("org. PostgreSQL. Driver"
, "JDBC: PostgreSQL: // dburi: 5432/dbname"
, "Postgre"
, "Postgre ");
② Connpool. createpool ();
Connection conn = connpool. getconnection ();
*/