外文翻译3Stateless Session Beans的基础.docx
- 文档编号:29454873
- 上传时间:2023-07-23
- 格式:DOCX
- 页数:26
- 大小:29KB
外文翻译3Stateless Session Beans的基础.docx
《外文翻译3Stateless Session Beans的基础.docx》由会员分享,可在线阅读,更多相关《外文翻译3Stateless Session Beans的基础.docx(26页珍藏版)》请在冰豆网上搜索。
外文翻译3StatelessSessionBeans的基础
TheBasicsofStatefulSessionBeans
Statefulsessionbeansareconversationalbeansbecausetheyholdconversations
withclientsthatspanmultiplemethodinvocations.Statefulsessionbeansstore
conversationalstatewithinthebean.Thatconversationalstateisspecifictoa
particularclient.Thischapterwillteachyouthebasicsofwritingstatefulsession
beans.We’llbeginattheconceptuallevelandquicklymoveintoacodeexample
illustratingsessionbeandevelopment.We’llwrapupwithacomparison
ofthestatefulandstatelessprogrammingmodels.
CharacteristicsofStatefulSessionBeans
Let’sbeginwithalookatthecharacteristicsthatallstatefulsessionbeansshare.
AchievingtheEffectofPoolingwithStatefulBeans
Imagineascenariowherethousandsofclientsarehavingconversationswith
differentstatefulsessionbeansrunningwithinacontainer.Let’sassumethat
theclientsaretypicalclientsandtakealongtimeto“think”betweenmethod
calls.Perhapsaclientisfaraway,connectingfromanothercountry,andthe
networklagishigh.Orperhapstheclientrepresentsahumaninteractingwith
aJavaapplet,andthehumanisdecidingonthenextbuttontoclick.
Thousandsofclientsimplythousandsofstatefulsessionbeans,eachholding
conversationalstateonbehalfofaspecificclient.And,ofcourse,ourEJBcontainer/
serverhasonlyafiniteamountofresourcesavailable,suchasmemory,
databaseconnections,andsocketconnections.Iftheconversationalstatethat
thebeansareholdingislarge,thecontainer/servercouldeasilyrunoutofresources.
Thiswasnotaproblemwithstatelesssessionbeansbecausethecontainer
couldpoolonlyafewbeanstoservicethousandsofclients.
Withstatefulsessionbeans,poolingisnotassimple.Whenaclientinvokesa
methodonabean,heorsheisstartingaconversationwiththebean,andthe
conversationalstatestoredinthebeanmustbeavailableforthatsameclient’s
nextmethodrequest.Therefore,thecontainercannoteasilypoolbeansand
dynamicallyassignthemtohandlearbitraryclientmethodrequests,sinceeach
beanisstoringstateonbehalfofaparticularclient.Butwestillneedtoachieve
theeffectofpoolingforstatefulsessionbeans,sothatwecanconserveresources
andenhancetheoverallscalabilityofthesystem.
Thisproblemshouldsoundquitefamiliartooperatingsystemsgurus.Whenever
yourunanapplicationonacomputer,youhaveonlyafixedamountofphysical
memoryinwhichtorun.Theoperatingsystemstillmustprovideawayfor
manyapplicationstorun,eveniftheapplicationstakeupmoreaggregate
memorythanisavailablephysically.Toprovideforthis,operatingsystemsuse
yourharddiskasanextensionofphysicalmemory.Thiseffectivelyextendsthe
amountofvirtualmemorythatyoursystemhas.Whenanapplicationgoesidle,
itsmemorycanbeswappedoutfromphysicalmemoryandontotheharddisk.
Whentheapplicationbecomesactiveagain,anyneededdataisswappedinfrom
theharddiskandintophysicalmemory.Thistypeofswappinghappensvery
oftenwhenswitchingbetweenapplications(calledcontextswitching).
EJBcontainersexploitthisveryparadigmtoconservestatefulsessionbean
resources.Tolimitthenumberofstatefulsessionbeaninstancesinmemory,
thecontainercanswapoutastatefulbean,savingitsconversationalstatetoa
harddiskorotherstorage.Thisiscalledpassivation.Afterpassivatingastateful
bean,theconversationalstateissafelystoredaway,allowingresourcessuch
asmemorytobereclaimed.Whentheoriginalclientinvokesamethod,thepassivated
conversationalstateisswappedintoabean.Thisiscalledactivation.
Thisbeannowresumestheconversationwiththeoriginalclient.Notethatthe
beanthatreceivestheactivatedstatemaynotbetheoriginalbeaninstance.But
that’sallrightbecausetheinstanceisresumingitsconversationfromthepoint
wheretheoriginalinstancewaspassivated.
Thus,EJBdoesindeedsupporttheeffectofpoolingstatefulsessionbeans.Only
afewinstancescanbeinmemorywhenthereareactuallymanyclients.Butthis
poolingeffectdoesnotcomeforfree—thepassivation/activationstepscould
entailanI/Obottleneck.Contrastthistostatelesssessionbeans,whichareeasily
pooledbecausethereisnostatetosave.
Sohowdoesthecontainerdecidewhichbeanstoactivateandwhichbeansto
passivate?
Theanswerisspecifictoeachcontainer.Mostcontainerswillemploy
aLeastRecentlyUsed(LRU)passivationstrategy,whichsimplymeansto
passivatethebeanthathasbeencalledtheleastrecently.Thisisagoodalgorithm
becauseremoteclientshavethehabitofdisconnectingfromthenetwork,
leavingbeansstrandedwithoutaclient,readytobepassivated.Ifabeanhasn’t
beeninvokedinawhile,thecontainerwillwriteittodisk.
Passivationcanoccuratanytime,solongasabeanisnotinvolvedinamethod
call.It’suptothecontainertodecidewhenpassivationmakessense.Notethat
thereisoneexceptiontothisrule:
Anybeaninvolvedinatransaction(see
Chapter10)cannotbepassivateduntilthetransactioncompletes.
Toactivatebeans,mostcontainerswillusuallyuseajust-in-timealgorithm.Just
intimemeansthatbeansshouldbeactivatedondemand,asclientrequestscome
in.Ifaclientrequestcomesinbutthatclient’sconversationhasbeenpassivated,
thecontainerwillactivatethebeanondemand,readingthepassivatedstateback
intomemory.
Ingeneral,passivationandactivationarenotusefulforstatelesssessionbeans.
Statelessbeansdonothaveanystatetopassivate/activate,andsostatelessbeans
cansimplybedestroyedarbitrarilybythecontainer.Passivation/activationalso
appliestoentitybeans,whichwe’lllearnaboutinChapters7–9.
TheRulesGoverningConversationalState
Aswehavesaid,statefulsessionbeansholdconversationalstateonbehalfof
oneclient.Let’sdefinethatstateabitmorerigorously.It’simportanttoknow
therulesforspecifyingconversationalstate,sothatthecontainerwillpassivate
andactivateproperly.
TheconversationalstateofabeanfollowstheruleslaidoutbyJavaobjectserialization
(seeAppendixA).Whenacontainerpassivatesabean,itusesobject
serialization(oranequivalentprotocol)toconvertthebean’sconversational
stateintoabit-blob.Itcanthenwritethatblobouttostorage.Oncethebeanis
writtentostorage,thememoryisavailabletobefreedbythegarbagecollector.
Activationreversestheprocess—aserializedblobthathadbeenwrittentostorage
isreadbackintomemoryandconvertedtoin-memorybeandata.What
makesthiswholeprocessworkisthejavax.ejb.EnterpriseBeaninterfaceextends
java.io.Serializable,andeveryenterprisebeanclassindirectlyimplements
thisinterface.
Moreconcretely,everymembervariableinabeanisconsideredtobepartof
thebean’sconversationalstateifthefollowingapply:
__Themembervariableisanontransientprimitivetype,or
__ThemembervariableisanontransientJavaobject(extends
java.lang.Object).
ForeveryJavaobjectthat’spartofabean’sconversationalstate,theprevious
algorithmisreappliedrecursivelyonthoseobjects.Thus,objectserialization
constructsanentiregraphofdatareferredtobythemainbean.Youshouldnote
thatwhileyourbeansmustfollowtherulesforobjectserialization,theEJB
containeritselfdoesnotnecessarilyneedtousethedefaultserializationprotocol;
itcoulduseacustomprotocolforthis,toallowflexibilityanddifferentiation
betweencontainervendors.
Activation/PassivationCallbacks
Let’snowlookatwhatactuallyhappenstoyourbeanduringpassivationand
activation.WhenanEJBcontainerpassivatesabean,thecontainerwritesthe
bean’sconversationalstatetosecondarystorage,suchasafileordatabase.The
containerinformsthebeanthatit’sabouttoperformpassivationbycalling
thebean’srequiredejbPassivate()callbackmethod.ejbPassivate()isawarning
tothebeanthatitsheldconversationalstateisabouttobeswappedout.
It’simportantthatthecontainerinformthebeanusingejbPassivate()sothat
thebeancanrelinquishheldresources.Theseheldresourcesincludedatabase
connections,opensockets,openfiles,orotherresourcesthatdonotmakesense
tobesavedtodiskorcannotbetransparentlysavedusingobjectserialization.
TheEJBcontainercallstheejbPassivate()methodtogivethebeanachance
toreleasetheseresourcesordealwiththeresourcesasthebeanseesfit.Once
thecontainer’sejbPassivate()callbackmethodintoyourbeaniscomplete,your
beanmustbeinastatesuitableforpassivation.ThisisshowninFigure5.1.
Theexactoppositeprocessoccursduringtheactivationprocess.Here,theserialized
conversationalstateisreadbackintomemory,andthecontainerreconstructs
thein-memorystateusingobjectserializationortheequivalent.The
containerthencallsthebean’srequiredejbActivate()method.ejbActivate()gives
thebeanachancetorestoretheopenresourcesitreleasedduringejbPassivate().
ThisentireprocessisshowninFigure5.2.
DoyouhavetoworryaboutimplementingejbPassivate()andejbActivate()?
Probablynot,unlessyouareusingopenresources,suchassocketconnections
ordatabaseconnections,thatmustbereestablishedafteractivation.Inmost
cases,youcansimplyleavethesemethodsempty.
ASimpleStatefulSessionBean
Let’sputourstatefulsessionbeanknowledgetousebyprogrammingasimple
statefulbean.Ourbeanwillbeacounterbean,anditwillsimplyberesponsible
forcountinguponebyone.Thecurrentcountwillbestor
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 外文翻译3Stateless Session Beans的基础 外文 翻译 Stateless Beans 基础
![提示](https://static.bdocx.com/images/bang_tan.gif)