System scenario: The system relies on multiple databases. One of the database servers runs Oracle, and there are several machines running the Objectserver memory database. You need to dynamically create a connection pool because you can determine the number of machines from the deployment
Scenario: Oracle databases use C3P0 to manage connection pooling. Write another connection manager to dynamically create a memory database connection pool
Code: Simplified, only to post key code, remove log, exception handling, NULL check, etc.
Obejctserver connection pool, the number of domains in the system corresponds to the public
class Dbconnectionpool
{
private int checkedout;//The number of connections checked out by the class instance one by one
private Vector<connection> freeconnections = new vector<connection> ()//Free connection number
//return connection
Public synchronized void freeconnection (Connection con, Object Lock)
{
freeconnections.addelement (con);
this.checkedout--;
Lock.notifyall ();
}
Get connection from Connection pool public
Connection getconnection (Object Lock)
{
Connection con;
while (con = fetchconnection ()) = = null)//Loop call Fetchconnection () method
{
lock.wait (timeout);
//If timed out, return null
}
Return con.
}
}
Objectserver Connection Manager public class Dbconnectionmanager {private hashtable<string, dbconnectionpool> pools;//connection Pool collection, each OS domain has a connection pool private static final byte[] lock = new byte[0];//sync lock//return connection public void Freeco Nnection (String DomainName, Connection conn) {synchronized (lock) {DbConnection
Pool pool = (dbconnectionpool) pools.get (domainname);//Get the domain name corresponding to the connection pooling pool.freeconnection (conn, lock); }///Get the available connection from the machine public Connection getconnection (String domainname) {Synchro
Nized (lock) {Dbconnectionpool pool = (dbconnectionpool) pools.get (domainname);
if (null!= pool)//connection pool already exists, use {return pool.getconnection (lock) directly;
else {registernewconnectionpool (poolprovide);//Register New Connection pool Return getconnection (DoMainname);//Recursive Call} return null;
}
}
}