|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
恰恰证明了java的简单,要不怎么没有通过c/c++来搞个这种框架?
/**
*Thismethodhandsouttheconnectionsinround-robinorder.
*Thispreventsafaultyconnectionfromlocking
*upanapplicationentirely.Abrowserrefreshwill
*getthenextconnectionwhilethefaulty
*connectioniscleanedupbythehousekeepingthread.
*
*Iftheminnumberofthreadsareeverexhausted,new
*threadsareaddedupthethemaxthreadcount.
*Finally,ifallthreadsareinuse,thismethodwaits
*2secondsandtriesagain,uptotentimes.Afterthat,it
*returnsanull.
*/
publicConnectiongetConnection(){
Connectionconn=null;
if(available){
booleangotOne=false;
for(intouterloop=1;outerloop<=10;outerloop++){
try{
intloop=0;
introundRobin=connLast+1;
if(roundRobin>=currConnections)roundRobin=0;
do{
synchronized(connStatus){
if((connStatus[roundRobin]<1)&&
(!connPool[roundRobin].isClosed()))
{
conn=connPool[roundRobin];
connStatus[roundRobin]=1;
connLockTime[roundRobin]=
System.currentTimeMillis();
connLast=roundRobin;
gotOne=true;
break;
}
else{
loop++;
roundRobin++;
if(roundRobin>=currConnections)roundRobin=0;
}
}
}
while((gotOne==false)&&(loop<currConnections));
}
catch(SQLExceptione1){}
if(gotOne){
break;
}
else{
synchronized(this){//Addnewconnectionstothepool
if(currConnections<maxConns){
try{
createConn(currConnections);
currConnections++;
}
catch(SQLExceptione){
log.println("Unabletocreatenewconnection:"+e);
}
}
}
try{Thread.sleep(2000);}
catch(InterruptedExceptione){}
log.println("----->ConnectionsExhausted!Willwaitandtry"+
"againinloop"+
String.valueOf(outerloop));
}
}//Endoftry10timesloop
}
else{
log.println("UnsuccessfulgetConnection()requestduringdestroy()");
}//Endif(available)
returnconn;
}
/**
*ReturnsthelocalJDBCIDforaconnection.
*/
publicintidOfConnection(Connectionconn){
intmatch;
Stringtag;
try{
tag=conn.toString();
}
catch(NullPointerExceptione1){
tag="none";
}
match=-1;
for(inti=0;i<currConnections;i++){
if(connID[i].equals(tag)){
match=i;
break;
}
}
returnmatch;
}
/**
*Freesaconnection.Replacesconnectionbackintothemainpoolfor
*reuse.
*/
publicStringfreeConnection(Connectionconn){
Stringres="";
intthisconn=idOfConnection(conn);
if(thisconn>=0){
connStatus[thisconn]=0;
res="freed"+conn.toString();
//log.println("Freedconnection"+String.valueOf(thisconn)+
//"normalexit:");
}
else{
log.println("---->Couldnotfreeconnection!!!");
}
returnres;
}
//文件:DbConnectionDefaultPool.java的第三部分
/**
*Returnstheageofaconnection--thetimesinceitwashandedoutto
*anapplication.
*/
publiclonggetAge(Connectionconn){//Returnstheageoftheconnectioninmillisec.
intthisconn=idOfConnection(conn);
returnSystem.currentTimeMillis()-connLockTime[thisconn];
}
privatevoidcreateConn(inti)throwsSQLException{
Datenow=newDate();
try{
Class.forName(dbDriver);
PropertiesdbProp=newProperties();
//log.println("Creating.....");
dbProp.put("user",dbLogin);
dbProp.put("password",dbPassword);
dbProp.put("characterEncoding","gb2112");
//dbProp.put("useUnicode","true");
connPool[i]=DriverManager.getConnection
(dbServer,dbProp);
//log.println("CreatedOk...");
connStatus[i]=0;
connID[i]=connPool[i].toString();
connLockTime[i]=0;
connCreateDate[i]=now.getTime();
}
catch(ClassNotFoundExceptione2){}
log.println(now.toString()+"Openingconnection"+String.valueOf(i)+
""+connPool[i].toString()+":");
}
/**
*Shutsdownthehousekeepingthreadandclosesallconnections
*inthepool.Callthismethodfromthedestroy()methodoftheservlet.
*/
/**
*Multi-phaseshutdown.havingfollowingsequence:
*<OL>
*<LI><code>getConnection()</code>willrefusetoreturnconnections.
*<LI>Thehousekeepingthreadisshutdown.<br>
*Uptothetimeof<code>millis</code>millisecondsaftershutdownof
*thehousekeepingthread,<code>freeConnection()</code>canstillbe
*calledtoreturnusedconnections.
*<LI>After<code>millis</code>millisecondsaftertheshutdownofthe
*housekeepingthread,allconnectionsinthepoolareclosed.
*<LI>Ifanyconnectionswereinusewhilebeingclosedthena
*<code>SQLException</code>isthrown.
*<LI>Thelogisclosed.
*</OL><br>
*Callthismethodfromaservletdestroy()method.
*
*@parammillisthetimetowaitinmilliseconds.
*@exceptionSQLExceptionifconnectionswereinuseafter
*<code>millis</code>.
*/
publicvoiddestroy(intmillis)throwsSQLException{
//Checkingforinvalidnegativeargumentsisnotnecessary,
//Thread.join()doesthisalreadyinrunner.join().
//Stopissuingconnections
available=false;
//Shutdownthebackgroundhousekeepingthread
runner.interrupt();
//Waituntilthehousekeepingthreadhasdied.
try{runner.join(millis);}
catch(InterruptedExceptione){}//ignore
//Thehousekeepingthreadcouldstillberunning
//(e.g.ifmillisistoosmall).Thiscaseisignored.
//Atworst,thismethodwillthrowanexceptionwiththe
//clearindicationthatthetimeoutwastooshort.
longstartTime=System.currentTimeMillis();
//WaitforfreeConnection()toreturnanyconnections
//thatarestillusedatthistime.
intuseCount;
while((useCount=getUseCount())>0&&System.currentTimeMillis()-startTime<=millis){
try{Thread.sleep(500);}
catch(InterruptedExceptione){}//ignore
}
//Closeallconnections,whethersafeornot
for(inti=0;i<currConnections;i++){
try{
connPool[i].close();
}
catch(SQLExceptione1)
{
log.println("CannotcloseconnectionsonDestroy");
}
}
if(useCount>0){
//bt-testsuccessful
Stringmsg="Unsafeshutdown:Hadtoclose"+useCount+
"activeDBconnectionsafter"+millis+"ms";
log.println(msg);
//Closeallopenfiles
log.close();
//ThrowingfollowingExceptionisessentialbecauseservletauthors
//arelikelytohavetheirownerrorloggingrequirements.
thrownewSQLException(msg);
}
//Closeallopenfiles
log.close();
}//Enddestroy()
/**
*Lesssafeshutdown.Usesdefaulttimeoutvalue.
*Thismethodsimplycallsthe<code>destroy()</code>method
*witha<code>millis</code>
*valueof10000(10seconds)andignores<code>SQLException</code>
*thrownbythatmethod.
*@see#destroy(int)
*/
publicvoiddestroy(){
try{
destroy(10000);
}
catch(SQLExceptione){}
}
/**
*Returnsthenumberofconnectionsinuse.
*/
//Thismethodcouldbereducedtoreturnacounterthatis
//maintainedbyallmethodsthatupdateconnStatus.
//However,itismoreefficienttodoitthiswaybecause:
//Updatingthecounterwouldputanadditionalburdenonthemost
//frequentlyusedmethods;incomparison,thismethodis
//rarelyused(althoughessential).
publicintgetUseCount(){
intuseCount=0;
synchronized(connStatus){
for(inti=0;i<currConnections;i++){
if(connStatus[i]>0){//Inuse
useCount++;
}
}
}
returnuseCount;
}//EndgetUseCount()
/**
*Returnsthenumberofconnectionsinthedynamicpool.
*/
publicintgetSize(){
returncurrConnections;
}//EndgetSize()
}
/**
*AnimplementationoftheConnectioninterfacethatwrapsanunderlying
*Connectionobject.Itreleasestheconnectionbacktoaconnectionpool
*whenConnection.close()iscalled.
*/
publicclassConnectionWrapperimplementsConnection{
privateConnectionconnection;
privateConnectionPoolconnectionPool;
publicConnectionWrapper(Connectionconnection,ConnectionPoolconnectionPool){
this.connection=connection;
this.connectionPool=connectionPool;
}
/**
*Insteadofclosingtheunderlyingconnection,wesimplyrelease
*itbackintothepool.
*/
publicvoidclose()throwsSQLException{
connectionPool.freeConnection(this.connection);
//Releaseobjectreferences.Anyfurthermethodcallsonthe
//connectionwillfail.
connection=null;
connectionPool=null;
}
publicStatementcreateStatement()throwsSQLException{
returnconnection.createStatement();
}
publicPreparedStatementprepareStatement(Stringsql)throwsSQLException{
returnconnection.prepareStatement(sql);
}
publicCallableStatementprepareCall(Stringsql)throwsSQLException{
returnconnection.prepareCall(sql);
}
publicStringnativeSQL(Stringsql)throwsSQLException{
returnconnection.nativeSQL(sql);
}
publicvoidsetAutoCommit(booleanautoCommit)throwsSQLException{
connection.setAutoCommit(autoCommit);
}
publicbooleangetAutoCommit()throwsSQLException{
returnconnection.getAutoCommit();
}
publicvoidcommit()throwsSQLException{
connection.commit();
}
publicvoidrollback()throwsSQLException{
connection.rollback();
}
publicbooleanisClosed()throwsSQLException{
returnconnection.isClosed();
}
publicDatabaseMetaDatagetMetaData()throwsSQLException{
returnconnection.getMetaData();
}
publicvoidsetReadOnly(booleanreadOnly)throwsSQLException{
connection.setReadOnly(readOnly);
}
publicbooleanisReadOnly()throwsSQLException{
returnconnection.isReadOnly();
}
publicvoidsetCatalog(Stringcatalog)throwsSQLException{
connection.setCatalog(catalog);
}
publicStringgetCatalog()throwsSQLException{
returnconnection.getCatalog();
}
publicvoidsetTransactionIsolation(intlevel)throwsSQLException{
connection.setTransactionIsolation(level);
}
publicintgetTransactionIsolation()throwsSQLException{
returnconnection.getTransactionIsolation();
}
publicSQLWarninggetWarnings()throwsSQLException{
returnconnection.getWarnings();
}
publicvoidclearWarnings()throwsSQLException{
connection.clearWarnings();
}
publicStatementcreateStatement(intresultSetType,intresultSetConcurrency)
throwsSQLException
{
returnconnection.createStatement(resultSetType,resultSetConcurrency);
}
publicPreparedStatementprepareStatement(Stringsql,intresultSetType,
intresultSetConcurrency)throwsSQLException
{
returnconnection.prepareStatement(sql,resultSetType,resultSetConcurrency);
}
publicCallableStatementprepareCall(Stringsql,intresultSetType,
intresultSetConcurrency)throwsSQLException
{
returnprepareCall(sql,resultSetType,resultSetConcurrency);
}
publicMapgetTypeMap()throwsSQLException{
returnconnection.getTypeMap();
}
publicvoidsetTypeMap(Mapmap)throwsSQLException{
connection.setTypeMap(map);
}
}
}//文件:DbConnectionManager.java
packagecom.qingtuo.db.pool;
importjava.sql.*;
importjava.io.*;
importjava.util.*;
/**
*Centralmanagerofdatabaseconnections.
*/
publicclassDbConnectionManager{
privatestaticDbConnectionProviderconnectionProvider;
privatestaticObjectproviderLock=newObject();
/**
*Returnsadatabaseconnectionfromthecurrentlyactiveconnection
*provider.
*/
publicstaticConnectiongetConnection(){
if(connectionProvider==null){
synchronized(providerLock){
if(connectionProvider==null){
//Createtheconnectionprovider--fornow,thisishardcoded.For
//thenextbeta,Illchangethistoloaduptheproviderdynamically.
connectionProvider=newDbConnectionDefaultPool();
connectionProvider.start();
}
}
}
Connectioncon=connectionProvider.getConnection();
if(con==null){
System.err.println("WARNING:DbConnectionManager.getConnection()failedtoobtainaconnection.");
}
returncon;
}
/**
*Returnsthecurrentconnectionprovider.Theonlycaseinwhichthis
*methodshouldbecalledisifmoreinformationaboutthecurrent
*connectionproviderisneeded.Databaseconnectionsshouldalwaysbe
*obtainedbycallingthegetConnectionmethodofthisclass.
*/
publicstaticDbConnectionProvidergetDbConnectionProvider(){
returnconnectionProvider;
}
/**
*Setstheconnectionprovider.Theoldprovider(ifitexists)isshut
*downbeforethenewoneisstarted.Aconnectionprovider<b>should
*not</b>bestartedbeforebeingpassedtotheconnectionmanager.
*/
publicstaticvoidsetDbConnectionProvider(DbConnectionProviderprovider){
synchronized(providerLock){
if(connectionProvider!=null){
connectionProvider.destroy();
connectionProvider=null;
}
connectionProvider=provider;
provider.start();
}
}
}
而学习JAVA我觉得最应该避免的就是:只学习,不思考,只记忆,不实践! |
|