The manager of the connection pool, initialized first, has only one object, manages the connection pool
private static HashMap connectionpoolmanager=new HashMap ();
No used connection pool, using vector to achieve synchronization
private static Vector Nouseconnectionpool;
No used connection pool
private static HashMap Nowuseconnectionpool;
Get a real link through a connection pool
public static Connection getconnection () throws java.sql.sqlexception{
Connection Conn=null;
Synchronized (Nouseconnectionpool) {
if (Nouseconnectionpool.size () >0) {
Conn= (Connection) nouseconnectionpool.firstelement ();
Nouseconnectionpool.remove (conn);
Return conn;
}
}
If the database connection pool does not have a link, create a
if (conn==null) {
Conn=createconnection (Dbdriver,dburl,username,userpassword);
}else if (conn.isclosed ()) {
Nowuseconnectionpool.remove (conn);
Conn=createconnection (Dbdriver,dburl,username,userpassword);
}
Conn.setautocommit (FALSE);
Nowuseconnectionpool.put (Conn,conn);
Return conn;
}
If the connection pool is not linked, you need to produce a link
private static Connection createconnection (String driver,string url,string user,string password)
Throws java.sql.sqlexception{
Connection conn=drivermanager.getconnection (Url,user,password);
Return conn;
}
public static void Releaseconnection (Connection conn,boolean iscommit)
Throws java.sql.sqlexception{
if (iscommit)
Conn.commit ();
Else
Conn.rollback ();
Nowuseconnectionpool.remove (conn);
if (nouseconnectionpool.size () + nowuseconnectionpool.size () <max_pool) {
Synchronized (Nouseconnectionpool) {
NOUSECONNECTIONPOOL.ADD (conn);
}
}else{
Conn.close ();
}
}
public static void Main (string[] args) {
Test simulation 10 Customers
for (int i = 0; i < i++) {
try {
XXXX is typically read as a property file
ConnectionPool pool = connectionpool.getconnmanagerinstance ("xxxx");
Connection conn = Pool.getconnection ();
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