仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 876|回复: 18
打印 上一主题 下一主题

[学习教程] JAVA网页编程之一个毗连池的例子 (二)

[复制链接]
再见西城 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-18 11:37:44 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

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我觉得最应该避免的就是:只学习,不思考,只记忆,不实践!
飘灵儿 该用户已被删除
沙发
发表于 2015-1-21 11:33:26 | 只看该作者
Java自面世后就非常流行,发展迅速,对C++语言形成了有力冲击。Java 技术具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台
活着的死人 该用户已被删除
板凳
发表于 2015-1-21 11:33:27 | 只看该作者
你现在最缺的是实际的工作经验,而不是书本上那些凭空想出来的程序。
金色的骷髅 该用户已被删除
地板
发表于 2015-1-30 17:11:31 | 只看该作者
Java 编程语言的风格十分接近C、C++语言。
蒙在股里 该用户已被删除
5#
发表于 2015-2-5 12:04:33 | 只看该作者
Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。
admin 该用户已被删除
6#
发表于 2015-2-7 11:52:31 | 只看该作者
多重继承(以接口取代)等特性,增加了垃圾回收器功能用于回收不再被引用的对象所占据的内存空间,使得程序员不用再为内存管理而担忧。在 Java 1.5 版本中,Java 又引入了泛型编程(Generic Programming)、类型安全的枚举、不定长参数和自动装/拆箱等语言特性。
谁可相欹 该用户已被删除
7#
发表于 2015-2-20 14:11:31 | 只看该作者
任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的程序语言
冷月葬花魂 该用户已被删除
8#
发表于 2015-3-6 14:47:33 | 只看该作者
是一种使网页(Web Page)产生生动活泼画面的语言
兰色精灵 该用户已被删除
9#
发表于 2015-3-13 02:09:07 | 只看该作者
还好,SUN提供了Javabean可以把你的JSP中的 Java代码封装起来,便于调用也便于重用。
再见西城 该用户已被删除
10#
 楼主| 发表于 2015-3-18 19:35:07 | 只看该作者
科学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。
透明 该用户已被删除
11#
发表于 2015-3-23 21:52:13 | 只看该作者
Java是一种计算机编程语言,拥有跨平台、面向对java
柔情似水 该用户已被删除
12#
发表于 2015-4-2 20:44:05 | 只看该作者
我大二,Java也只学了一年,觉得还是看thinking in java好,有能力的话看英文原版(中文版翻的不怎么好),还能提高英文文档阅读能力。
简单生活 该用户已被删除
13#
发表于 2015-4-6 10:58:05 | 只看该作者
象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。
莫相离 该用户已被删除
14#
发表于 2015-4-6 19:10:14 | 只看该作者
象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。
15#
发表于 2015-4-12 04:52:33 | 只看该作者
Java 编程语言的风格十分接近C、C++语言。
愤怒的大鸟 该用户已被删除
16#
发表于 2015-4-15 19:05:02 | 只看该作者
应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展
乐观 该用户已被删除
17#
发表于 2015-4-18 14:50:29 | 只看该作者
Pet Store.(宠物店)是SUN公司为了演示其J2EE编程规范而推出的开放源码的程序,应该很具有权威性,想学J2EE和EJB的朋友不要 错过了。
精灵巫婆 该用户已被删除
18#
发表于 2015-4-26 00:09:23 | 只看该作者
有时间再研究一下MVC结构(把Model-View-Control分离开的设计思想)
再现理想 该用户已被删除
19#
发表于 2015-5-11 09:48:18 | 只看该作者
不过,每次的执行编译后的字节码需要消耗一定的时间,这同时也在一定程度上降低了 Java 程序的运行效率。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-12-23 02:20

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表