JAVA网页编程之一个毗连池的例子 (二)
恰恰证明了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<1)&&
(!connPool.isClosed()))
{
conn=connPool;
connStatus=1;
connLockTime=
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.equals(tag)){
match=i;
break;
}
}
returnmatch;
}
/**
*Freesaconnection.Replacesconnectionbackintothemainpoolfor
*reuse.
*/
publicStringfreeConnection(Connectionconn){
Stringres="";
intthisconn=idOfConnection(conn);
if(thisconn>=0){
connStatus=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;
}
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=DriverManager.getConnection
(dbServer,dbProp);
//log.println("CreatedOk...");
connStatus=0;
connID=connPool.toString();
connLockTime=0;
connCreateDate=now.getTime();
}
catch(ClassNotFoundExceptione2){}
log.println(now.toString()+"Openingconnection"+String.valueOf(i)+
""+connPool.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.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>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我觉得最应该避免的就是:只学习,不思考,只记忆,不实践! Java自面世后就非常流行,发展迅速,对C++语言形成了有力冲击。Java 技术具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台 你现在最缺的是实际的工作经验,而不是书本上那些凭空想出来的程序。 Java 编程语言的风格十分接近C、C++语言。 Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。 多重继承(以接口取代)等特性,增加了垃圾回收器功能用于回收不再被引用的对象所占据的内存空间,使得程序员不用再为内存管理而担忧。在 Java 1.5 版本中,Java 又引入了泛型编程(Generic Programming)、类型安全的枚举、不定长参数和自动装/拆箱等语言特性。 任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的程序语言 是一种使网页(Web Page)产生生动活泼画面的语言 还好,SUN提供了Javabean可以把你的JSP中的 Java代码封装起来,便于调用也便于重用。 科学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。 Java是一种计算机编程语言,拥有跨平台、面向对java 我大二,Java也只学了一年,觉得还是看thinking in java好,有能力的话看英文原版(中文版翻的不怎么好),还能提高英文文档阅读能力。 象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。 象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。 Java 编程语言的风格十分接近C、C++语言。 应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展 Pet Store.(宠物店)是SUN公司为了演示其J2EE编程规范而推出的开放源码的程序,应该很具有权威性,想学J2EE和EJB的朋友不要 错过了。 有时间再研究一下MVC结构(把Model-View-Control分离开的设计思想) 不过,每次的执行编译后的字节码需要消耗一定的时间,这同时也在一定程度上降低了 Java 程序的运行效率。
页:
[1]