Fully functional Java Connection pool invocation instance

Source: Internet
Author: User

/**
* Title:ConnectPool.java
* Description: Connection pool Manager
* Copyright:copyright © 2002/12/25
* Company:
* Author:
* Version 2.0
*/


Import java.io.*;
Import java.sql.*;
Import java.util.*;
Import Java.util.Date;

/**
* Management class Dbconnectionmanager support for one or more database connections defined by the properties file
* Pool Access. The client program can call the GetInstance () method to access the unique instance of this class.
*/
public class Connectpool
{
static public Connectpool instance; Unique instances
static public int clients;
Public vector drivers = new vector (); Driven
public PrintWriter log;
Public Hashtable pools = new Hashtable (); Connection

/**
* Returns a unique instance. If this method is called for the first time, the instance is created
*
* @return Dbconnectionmanager only Instance
*/
Static synchronized public Connectpool getinstance ()
{
if (instance = = null)
{
Instance = new Connectpool ();
}

clients++;

return instance;
}

/**
* Constructor Private to prevent other objects from creating instances of this class
*/
Public Connectpool () {
Init ();
}

/**
* Return the Connection object to the connection pool specified by the name
*
* @param name of the connection pool defined in the properties file
* @param con Connection object
*/
public void Freeconnection (String name, Connection con)
{
Dbconnectionpool pool = (dbconnectionpool) pools.get (name);
if (pool! = null)
{
Pool.freeconnection (con);
}
Else
{
System.out.println ("Pool ==null");
}
clients--;
}

/**
* Get an available (idle) connection. If no connection is available and the number of connections is less than the maximum number of connections
* Limit, the new connection is created and returned
*
* @param name of the connection pool defined in the properties file
* @return Connection available connection or null
*/
Public Connection getconnection (String name)
{
Dbconnectionpool pool = (dbconnectionpool) pools.get (name);
if (pool! = null)
{
return Pool.getconnection ();
return Pool.returnconnection ();
}
return null;
}

/**
* Get an available connection. If no connection is available and the number of connections is less than the maximum number of connections,
* Creates and returns a new connection. Otherwise, wait for other threads to release the connection for the specified time.
*
* @param name Connection pool name
* @param time to wait in milliseconds
* @return Connection available connection or null
*/
Public Connection getconnection (String name, long time)
{
Dbconnectionpool pool = (dbconnectionpool) pools.get (name);
if (pool! = null)
{
Return pool.getconnection (time);
}
return null;
}

/**
* Close all connections, revoke the driver registration
*/
Public synchronized void release ()
{
Wait until the last client program calls
if (--clients! = 0)
{
Return
}

Enumeration allpools = Pools.elements ();
while (Allpools.hasmoreelements ())
{
Dbconnectionpool pool = (dbconnectionpool) allpools.nextelement ();
Pool.release ();
}
Enumeration alldrivers = Drivers.elements ();
while (Alldrivers.hasmoreelements ())
{
Driver Driver = (Driver) alldrivers.nextelement ();
try {
Drivermanager.deregisterdriver (driver);

Log ("revoke JDBC Driver" + driver.getclass (). GetName () + "registration");
}
catch (SQLException e)
{
Log (E, "cannot revoke the registration of the following JDBC drivers:" + driver.getclass (). GetName ());
}
}
}

/**
* Creates a connection pool instance based on the specified attribute.
*
* @param props Connection Pool Properties
*/
private void Createpools (Properties props)
{
Enumeration propnames = Props.propertynames ();
while (Propnames.hasmoreelements ())
{
String name = (string) propnames.nextelement ();
if (Name.endswith (". url")) {
String poolname = name.substring (0, Name.lastindexof ("."));
String url = props.getproperty (poolname + ". url");
if (url = = null) {
Log ("No connection pool" + poolname + "Specify URL");
Continue
}
String user = Props.getproperty (poolname + ". User");
String password = props.getproperty (poolname + ". Password");
String maxconn = props.getproperty (poolname + ". Maxconn", "0");
int Max;
try{
max = integer.valueof (maxconn). Intvalue ();
}
catch (NumberFormatException e)
{
Log (maximum number of connections for error: "+ Maxconn +". Connection pool: "+ poolname);
max = 0;
}
Dbconnectionpool pool = new Dbconnectionpool (poolname, url, user, password, max);
Pools.put (poolname, pool);
Log ("Connection pool successfully created" + poolname);
}
}
}

/**
* Read Property completion initialization
*/
private void Init ()
{
Try
{
Properties P = new properties ();
String configs = System.getproperty ("User.dir") + "//conf//db.properties";

System.out.println ("configs file Local at" +configs);
FileInputStream is = new FileInputStream (configs);
Properties Dbprops = new properties ();
Try
{
Dbprops.load (IS);
}
catch (Exception e)
{
SYSTEM.ERR.PRINTLN ("Cannot read the properties file." + "Make sure the db.properties is in the path specified by Classpath");
Return
}
String logFile = Dbprops.getproperty ("LogFile", "DBConnectionManager.log");
try{

Log = new PrintWriter (new FileWriter (LogFile, True), true);
}
catch (IOException E)
{
System.err.println ("Unable to open log file:" + logFile);
Log = new PrintWriter (SYSTEM.ERR);
}
Loaddrivers (Dbprops);
Createpools (Dbprops); }catch (Exception e) {}
}

/**
171 * mount and register all JDBC drivers
172 *
173 * @param Props Properties
174 */
private void Loaddrivers (Properties props)
{
String driverclasses = Props.getproperty ("Drivers");
StringTokenizer st = new StringTokenizer (driverclasses);
while (St.hasmoreelements ())
{
String driverclassname = St.nexttoken (). Trim ();
try{
Driver Driver = (Driver)
Class.forName (Driverclassname). newinstance ();
Drivermanager.registerdriver (driver);
Drivers.addelement (driver);
System.out.println (Driverclassname);
Log ("Successfully registering the JDBC driver" + driverclassname);
}
catch (Exception e)
{
Log ("Unable to register the JDBC driver:" +
Driverclassname + ", Error:" + E);
}
}
}

/**
* Write text information to the log file
*/
private void log (String msg)
{
Log.println (New Date () + ":" + msg);
}

/**
* Write text information and exceptions to the log file
*/
private void log (Throwable e, String msg)
{
Log.println (New Date () + ":" + msg);
E.printstacktrace (log);
}

/**
* This inner class defines a connection pool. It is able to create new connections as required until a predetermined
* Up to the number of connections. It verifies the validity of the connection before returning the connection to the client program.
*/

Class Dbconnectionpool
{
private int checkedout;
Private vector freeconnections = new vector ();
private int maxconn;
private String name;
private String password;
Private String URL;
Private String user;

/**
* Create a new connection pool
*
* @param name Connection pool name
* jdbc URL for @param URL database
* @param user Database account number, or null
* @param password password, or null
* @param maxconn The maximum number of connections that this connection pool allows to establish
*/
Public Dbconnectionpool (string name, string URL, String user, String Password,int maxconn)
{
THIS.name = name;
This. url = URL;
This.user = user;
This.password = password;
This.maxconn = Maxconn;
}
/**
* Return connections that are no longer used to the connection pool
*
* @param the connection released by the Con client program
*/
Public synchronized void freeconnection (Connection con) {
Joins the specified connection to the end of the vector
Try
{
if (con.isclosed ()) {System.out.println ("before Freeconnection con is closed");}
Freeconnections.addelement (con);
Connection contest = (Connection) freeconnections.lastelement ();
if (contest.isclosed ()) {System.out.println ("After Freeconnection contest is closed");}
Notifyall ();
}catch (SQLException e) {System.out.println (e);}
}

/**
* Get an available connection from the connection pool. If there is no idle connection and the current number of connections is less than the maximum connection
* Number limit, a new connection is created. If the connection that was originally registered as available is no longer valid, it is removed from the vector,
* Then recursively call yourself to try a new available connection.
*/
Public synchronized Connection getconnection ()
{
Connection con = null;
if (freeconnections.size () > 0)
{
Gets the first available connection in a vector
Con = (Connection) freeconnections.firstelement ();
Freeconnections.removeelementat (0);
try {
if (con.isclosed ())
{
Log ("Remove an invalid connection from connection pool" + name+ ");
System.out.println ("Remove an invalid connection from the connection pool" + name+ ");
Recursively calls itself, tries to get the available connections again
con = getconnection ();
}
}
catch (SQLException e)
{
Log ("Error deleting an invalid connection from connection pool" + name+ ");
System.out.println ("Remove an invalid connection error from connection pool" + name+ ");
Recursively calls itself, tries to get the available connections again
con = getconnection ();
}
if (Freeconnections.size () >maxconn)
{System.out.println ("Delete an overflow connection");
Releaseone ();
}
}


else if ((Maxconn = = 0) | | (Freeconnections.size () <maxconn))
{
con = newconnection ();
}

return con;
}

Public synchronized Connection returnconnection ()
{
Connection con = null;
Returns a new connection if idle is less than the maximum connection
if (Freeconnections.size () <maxconn)
{
con = newconnection ();
}
Returns an available old connection if idle is greater than the maximum connection
else if (freeconnections.size () >=maxconn)
{

Con = (Connection) freeconnections.firstelement ();
System.out.println ("[a connection pool available connections]:" + "[" +freeconnections.size () + "]");
Freeconnections.removeelementat (0);
System.out.println ("[B Connection pool available connections]:" + "[" +freeconnections.size () + "]");
Try
{
if (con.isclosed ())
{
Log ("Remove an invalid connection from connection pool" + name+ ");
System.out.println ("Remove an invalid connection from the connection pool" + name+ ");
ReturnConnection ();
}
}catch (SQLException e)
{
Log ("Error deleting an invalid connection from connection pool" + name+ ");
System.out.println ("Remove an invalid connection error from connection pool" + name+ ");
ReturnConnection ();
}
}
return con;
}

/**
* Get available connections from the connection pool. You can specify the maximum amount of time a client program can wait
* See previous getconnection () method.
*
* Wait time limit of @param timeout in milliseconds
*/
Public synchronized Connection getconnection (long timeout)
{
Long startTime = new Date (). GetTime ();
Connection con;
while (con = getconnection ()) = = null)
{
Try
{
Wait (timeout);
}
catch (Interruptedexception e) {}
if (new Date (). GetTime ()-startTime) >= timeout) {
Wait () is returned because of a timeout
return null;
}
}
return con;
}

/**
* Close all connections
*/
Public synchronized void release ()
{
Enumeration allconnections = Freeconnections.elements ();
while (Allconnections.hasmoreelements ())
{
Connection con = (Connection) allconnections.nextelement ();
try {
Con.close ();
Log ("Close connection pool" + name+ ");
}
catch (SQLException e)
{
Log (E, "Unable to close connection pool" + name+ ");
}
}
Freeconnections.removeallelements ();
}
/**
* Close a connection
*/
Public synchronized void Releaseone ()
{
if (Freeconnections.firstelement ()!=null)
{Connection con = (Connection) freeconnections.firstelement ();
try {
Con.close ();
SYSTEM.OUT.PRINTLN ("Close connection pool" + name+ "one Connection");
Log ("Close connection pool" + name+ ");
}
catch (SQLException e)
{

SYSTEM.OUT.PRINTLN ("Cannot close a connection in the connection pool" + name+ ");
Log (E, "Unable to close connection pool" + name+ ");
}
}
Else
{
System.out.println ("Releaseone () Bug ... ..... .... ... .... ..... .... ..... ..... ..... ..... ...............");

}
}

/**
* Create a new connection
*/
Private Connection newconnection ()
{
Connection con = null;
Try
{
if (user = = null) {
con = drivermanager.getconnection (URL);
}
else{
con = drivermanager.getconnection (URL, user, password);
}
Log ("Connection pool" + name+ "create a new Connection");

}
catch (SQLException e) {
Log (E, "Unable to create a connection to the following URL:" + URL);
return null;
}
return con;
}
}
}

================================
/**
* Title:ConnectPool.java
* Description: Database operation
* Copyright:copyright &copy; 2002/12/25
* Company:
* Author:
* Remark: Add pointer rollback
* Version 2.0
*/

Import java.io.*;
Import com.sjky.pool.*;
Import java.sql.*;
Import java.util.*;
Import Java.util.Date;
Import java.net.*;

public class Poolman extends Connectpool {

Private Connectpool connmgr;
Private Statement stmt;
Private Connection con;
Private ResultSet rst;

/**
* Object Connection Initialization
* */

Public Connection Getpool (String name) throws Exception
{
try{
Connmgr = Connectpool.getinstance ();
con = connmgr.getconnection (name);
}catch (Exception e)
{
SYSTEM.ERR.PRINTLN ("Cannot create connection! Please try restarting the application Server");

}
return con;
}

/**
* Join the connection idle wait time with the above method
* How to use
* */

Public Connection getpool_t (String name, long time) throws Exception
{
try{
Connmgr = Connectpool.getinstance ();
con = connmgr.getconnection (name,time);
}catch (Exception e)
{
SYSTEM.ERR.PRINTLN ("Cannot create connection!");

}
return con;
}
/**
* Execute Query Method 1
* */
Public ResultSet executeQuery (String sqlstr) throws Exception
{
ResultSet result = null;
Try
{
stmt = Con.createstatement ();
result = Stmt.executequery (SQLSTR);
Here add one line by Jnma 12.11
Con.commit ();
}
catch (Java.sql.SQLException e)
{
throw new Exception ("Error executing query statement");
}
return result;
}
/**
* Execute Query Method 2
* */
Public ResultSet Getrst (String sqlstr) throws Exception
{
ResultSet result = null;
Try
{
stmt = Con.createstatement (resultset.type_scroll_sensitive,resultset.concur_updatable);
rst = Stmt.executequery (SQLSTR);
Here add one line by Jnma 12.11
Con.commit ();
}
catch (Java.sql.SQLException e)
{
throw new Exception ("Error executing query statement");
}
return rst;
}
/**
* Perform Updates
* */
public int Update (String sqlstr) throws Exception
{
int result =-1;
Try
{
stmt = Con.createstatement (resultset.type_scroll_sensitive,resultset.concur_updatable);
result = Stmt.executeupdate (SQLSTR);
Here add one line by Jnma 12.11
Con.commit ();
if (result==0)
SYSTEM.OUT.PRINTLN ("Error executing delete,update,insert SQL");
}
catch (Java.sql.SQLException e)
{
SYSTEM.ERR.PRINTLN ("Error executing delete,update,insert SQL");
}
return result;
}

/**
* Perform transaction processing
* */
public boolean handletransaction (Vector sqlarray) throws Exception
{
Boolean result = false;
int ArraySize = Sqlarray.size ();
Try
{
stmt = Con.createstatement ();
Con.setautocommit (FALSE);
System.out.println ("ArraySize is" +arraysize);
for (int i=0;i<arraysize;i++)
{
System.out.println ("Start execution statement" + (String) sqlarray.elementat (i));
Stmt.executeupdate (String) Sqlarray.elementat (i));
SYSTEM.OUT.PRINTLN ("Successful Execution");
}
Con.commit ();
Con.setautocommit (TRUE);//Must be
SYSTEM.OUT.PRINTLN ("Successful execution of the transaction");
result = true;
}
catch (Java.sql.SQLException e)
{
Try
{
System.out.println (E.tostring ());
SYSTEM.OUT.PRINTLN ("Database operation failed");
Con.rollback ();
}
catch (Java.sql.SQLException Te)
{
SYSTEM.ERR.PRINTLN ("Transaction error rollback exception");
}
}
Try
{
Con.setautocommit (TRUE);
}
catch (Java.sql.SQLException e)
{
System.err.println ("Set auto commit failed");
}
return result;
}

/**
* Release Connection
* */
public void Close (String name) throws Exception
{
Try
{
if (stmt!=null)
Stmt.close ();
if (con!=null)
{
Connmgr.freeconnection (Name,con);

System.out.println ("[C is releasing a connection]");

}
}
catch (Java.sql.SQLException e)
{
System.err.println ("Error releasing connection");
}
}

}
===========================
Property file Db.properties placed under Conf

#drivers =com.inet.tds.tdsdriver
#logfile =c://resin-2.1.4//dbconnectpool-log.txt
#test. maxconn=1000
#test. url=jdbc:inetdae:server:1433?sql7=true
#test. User=sa
#test. password=test

Drivers=com.microsoft.jdbc.sqlserver.sqlserverdriver
Logfile=f://resin-2.1.4//dbconnectpool-log.txt
Test.maxconn=20
Test.url=jdbc:microsoft:sqlserver://192.168.0.5:1433;databasename=test
Test.user=sa
Test.password=test


#drivers =oracle.jdbc.driver.oracledriver
#logfile =c://resin-2.1.4//dbconnectpool-log.txt
#test. maxconn=100
#test. Url=jdbc:oracle:thin:@192.168.0.10:1521:myhome
#test. User=system
#test. Password=manager
#mysql端3306

#drivers =org.gjt.mm.mysql.driver
#logfile =c://resin-2.1.4//dbconnectpool-log.txt
#test. maxconn=100
#test. url=jdbc:mysql://192.168.0.4:3306/my_test
#test. User=root
#test. Password=system

Fully functional Java Connection pool invocation instance

Related Article

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.