Tải bản đầy đủ - 0 (trang)
Chapter 3. Resource Management and the Primary Services

Chapter 3. Resource Management and the Primary Services

Tải bản đầy đủ - 0trang

3.1ResourceManagement

Alargebusinesssystemwithmanyuserscaneasilyrequire

thousandsofobjectsevenmillionsofobjectstobeinuse

simultaneously.Asthenumberofinteractionsamongthese

objectsincreases,concurrencyandtransactionalconcernscan

degradethesystem'sresponsetimeandfrustrateusers.EJB

serversincreaseperformancebysynchronizingobject

interactionsandsharingresources.

Thereisarelationshipbetweenthenumberofclientsandthe

numberofdistributedobjectsthatarerequiredtoservicethem.

Notsurprisingly,thelargertheclientpopulation,themore

distributedobjectsareneeded.Atsomepoint,theincreasein

clientsaffectsperformanceanddiminishesthroughput.EJB

explicitlysupportstwomechanismsthatmakeiteasierto

managelargenumbersofbeansatruntime:instancepooling

andactivation.Inaddition,EJBsupportstheuseoftheJ2EE

ConnectorArchitecture(J2EEConnectors)formanaging

resourceconnections.Asthenumberofdistributedobjectsand

clientsincrease,thenumberofresourceconnectionsalso

increases.J2EEConnectorsworkwiththeEJBcontainerto

manageconnectionstodatabases,enterprisemessaging,ERP,

legacysystems,andothertypesofresources.



3.1.1InstancePooling

Theconceptofpoolingresourcesisnothingnew.It'scommon

topooldatabaseconnectionssothatthebusinessobjectsinthe

systemcansharedatabaseaccess.Thistrickreducesthe

numberofdatabaseconnectionsneeded,whichreduces

resourceconsumptionandincreasesthroughput.TheJ2EE

ConnectorArchitecture(J2eeCA)isfrequentlythemechanism

employedbyEJBcontainerswhenpoolingconnectionsto



databasesandotherresources,andiscoveredalittlelater.

MostEJBcontainersalsoapplyresourcepoolingtoserver-side

components;thistechniqueiscalledinstancepooling.Instance

poolingreducesthenumberofcomponentinstancesand

thereforeresourcesneededtoserviceclientrequests.In

general,itisalsolessexpensivetoreusepooledinstancesthan

tocreateanddestroyinstances.

Asyoualreadyknow,clientsofsessionandentitybeans

interactwiththebeansthroughtheremoteandlocalinterfaces

implementedbyEJBobjects.Clientapplicationsneverhave

directaccesstotheactualbean.Similarly,JMSclientsnever

interactwithJMS-basedmessage-drivenbeans(JMS-MDBs)

directly.TheysendmessagesthatareroutedtotheEJB

containersystem.TheEJBcontainerthendeliversthese

messagestothepropermessage-driveninstance.

Instancepoolingispossiblebecauseclientsneveraccessbeans

directly.Therefore,there'snofundamentalreasontokeepa

separatecopyofeachenterprisebeanforeachclient.The

servercankeepamuchsmallernumberofenterprisebeans

aroundtodothework,reusingeachenterprisebeaninstanceto

servicedifferentrequests.Althoughthissoundslikearesource

drain,whendonecorrectly,itgreatlyreducestheresources

requiredtoservicealltheclientrequests.



3.1.1.1Theentitybeanlifecycle

Tounderstandhowinstancepoolingworks,let'sexaminethe

lifecycleofanentitybean.Entitybeansexistinoneofthree

states:



Nostate

Whenabeaninstanceisinthisstate,ithasnotyetbeen



instantiated.Weidentifythisstatetoprovideabeginning

andanendforthelifecycleofabeaninstance.



Pooledstate

Whenaninstanceisinthisstate,ithasbeeninstantiated

bythecontainerbuthasnotyetbeenassociatedwithan

EJBobject.



Readystate

Whenabeaninstanceisinthisstate,ithasbeenassociated

withanEJBobjectandisreadytorespondtobusiness

methodinvocations.

EachEJBvendorimplementsinstancepoolingdifferently,butall

instance-poolingstrategiesattempttomanagecollectionsof

beaninstancessothattheyarequicklyaccessibleatruntime.

Tosetupaninstancepool,theEJBcontainercreatesseveral

instancesofabeanclassandholdsthemuntilneeded.As

clientsmakebusiness-methodrequests,beaninstancesfrom

thepoolareassignedtotheEJBobjectsassociatedwiththe

clients.WhentheEJBobjectdoesn'tneedtheinstance,it's

returnedtotheinstancepool.AnEJBservermaintainsinstance

poolsforeverytypeofbeandeployed.Everyinstanceinan

instancepoolisequivalenttheyaretreatedequally.Instances

areselectedarbitrarilyfromtheinstancepoolandassignedto

EJBobjectsasneeded.

Afterthebeaninstanceisplacedinthepool,itgetsareference

toajavax.ejb.EJBContext.TheEJBContextprovidesan

interfacethatthebeancanusetocommunicatewiththeEJB

environment.ThisEJBContextbecomesmoreusefulwhenthe

beaninstancemovestotheReadystate.Whenaclientusesan



EJBhometoobtainaremoteorlocalreferencetoabean,the

containerrespondsbycreatinganEJBobject.Oncecreated,the

EJBobjectisassignedabeaninstancefromtheinstancepool.

WhenabeaninstanceisassignedtoanEJBobject,itofficially

enterstheReadystate.FromtheReadystate,abeaninstance

canreceiverequestsfromtheclientandcallbacksfromthe

container.Figure3-1showsthesequenceofeventsthatresults

inanEJBobjectwrappingabeaninstanceandservicinga

client.



Figure3-1.Abeanmovesfromtheinstancepool

totheReadystate



WhenabeaninstancemovesintotheReadystate,the

EJBContexttakesonnewmeaning.TheEJBContextprovides

informationabouttheclientthatisusingthebean.Italso



providestheinstancewithaccesstoitsownEJBhomeandEJB

object,whichisusefulwhenthebeanneedstopassreferences

toitselfortootherenterprisebeans,orwhenitneedsto

create,locate,orremovebeansofitsownclass.Sothe

EJBContextisnotastaticclass;itisaninterfacetothe

container,anditsstatechangesastheinstanceisassignedto

differentEJBobjects.

Whentheclientisfinishedwithabean'sremotereference,

eithertheremotereferencepassesoutofscopeoroneofthe

bean'sremovemethodsiscalled.[1]Atthispoint,thebean

instanceisdisassociatedfromtheEJBobjectandreturnedto

theinstancepool.Beaninstancescanalsobereturnedtothe

poolduringlullsbetweenclientrequests.Ifaclientrequestis

receivedandnobeaninstanceisassociatedwiththeEJBobject,

aninstanceisretrievedfromthepoolandassignedtotheEJB

object.Thisiscalledinstanceswapping.Afterthebeaninstance

returnstotheinstancepool,itisagainavailabletoservicea

newclientrequest.Figure3-2illustratesthelifecycleofabean

instance.

[1]The



EJBHome,EJBLocalHome,EJBObject,and

EJBLocalObjectinterfacesalldefinemethodsthatcanbeusedtoremoveabean.



Figure3-2.Lifecycleofabeaninstance



Thenumberofinstancesinthepoolfluctuatesasinstancesare

assignedtoEJBobjectsandreturnedtothepool.Thecontainer

canalsomanagethenumberofinstancesinthepool,

increasingthecountwhenclientactivityincreasesandlowering

thecountduringlessactiveperiods.



3.1.1.2Instanceswapping

Statelesssessionbeansofferaparticularlypowerfulopportunity

toleverageinstancepooling.Becauseastatelesssessionbean

doesnotmaintainanystatebetweenmethodinvocations,every

methodinvocationoperatesindependently,performingitstask

withoutrelyingoninstancevariables.Thismeansthatany

statelesssessioninstancecanservicerequestsforanyEJB

objectofthepropertype.Thecontainercanthereforeswap

beaninstancesinandoutbetweenmethodinvocations.

Figure3-3illustratesinstanceswappingbetweenstateless

sessionbeanmethodinvocations.InFigure3-3(a),instanceA

isservicingabusinessmethodinvocationdelegatedbyEJB



object1.OnceinstanceAhasservicedtherequest,itmoves

backtotheinstancepool(Figure3-3(b)).Whenabusiness

methodinvocationonEJBobject2isreceived,instanceAis

associatedwiththatEJBobjectforthedurationoftheoperation

(Figure3-3(c)).WhileinstanceAisservicingEJBobject2,

anothermethodinvocationisreceivedbyEJBobject1fromthe

clientandisservicedbyinstanceB(Figure3-3(d)).



Figure3-3.Statelesssessionbeansinaswapping

strategy



Usingthisswappingstrategyallowsafewstatelesssession

beaninstancestoservehundredsofclients,becausethe

amountoftimeittakestoperformmostmethodinvocationsis

typicallymuchshorterthanthepausesbetweenmethod

invocations.Whenabeaninstanceisfinishedservicinga

requestforanEJBobject,itisimmediatelymadeavailableto



anyotherEJBobjectthatneedsit.Thisallowsfewerstateless

sessioninstancestoservicemorerequests,whichdecreases

resourceconsumptionandimprovesperformance.

Statelesssessionbeansaredeclared"stateless"inthe

deploymentdescriptor.Nothingintheclassdefinitionmarksa

sessionbeanasbeingstatelessorstateful.Onceabeanclassis

deployedasstateless,thecontainerassumesthatno

conversationalstateismaintainedbetweenmethodinvocations.

Soastatelessbeancanhaveinstancevariables,butbecause

beaninstancescanbeservicingseveraldifferentEJBobjects,

theyshouldnotbeusedtomaintainconversationalstate.



3.1.1.3Message-drivenbeansandinstance

pooling

Message-drivenbeans,likestatelesssessionbeans,donot

maintainstatespecifictoaclientrequest,whichmakesthem

excellentcandidatesforinstancepooling.

InmostEJBcontainers,eachtypeofmessage-drivenbeanhas

itsowninstancepoolthatservicesincomingmessages.JMSMDBssubscribetoaspecificmessagedestination,whichisa

kindofaddressusedwhensendingandreceivingmessages.

WhenaJMSclientsendsanasynchronousmessagetoa

destination,themessageisdeliveredtotheEJBcontainersof

thebeansthatsubscribetothedestination.TheEJBcontainer

determineswhichJMS-MDBsubscribestothatdestination,then

choosesaninstanceofthattypefromtheinstancepoolto

processthemessage.OncetheJMS-MDBinstancehasfinished

processingthemessage(whentheonMessage()method

returns),theEJBcontainerreturnstheinstancetoitsinstance

pool.Figure3-4illustrateshowclientrequestsareprocessedby

anEJBcontainer.



Figure3-4.JMS-MDBinstancepooling



InFigure3-4(a),thetopJMSclientdeliversamessageto

DestinationAandthebottomJMSclientdeliversamessageto

DestinationB.TheEJBcontainerchoosesaninstanceof

MessageDrivenBean_1toprocessthemessageintendedfor

DestinationAandaninstanceofMessageDrivenBean_2to

processthemessageintendedforDestinationB.Thebean

instancesareremovedfromthepoolandusedtoprocessthe

messages.

AmomentlaterinFigure3-4(b),themiddleJMSclientsendsa

messagetoDestinationB.Atthispoint,thefirsttwomessages

havealreadybeenprocessedandthecontainerisreturningthe

instancestotheirrespectivepools.Asthenewmessagecomes

in,thecontainerchoosesanewinstanceof

MessageDrivenBean_2toprocessthemessage.

JMS-MDBsarealwaysdeployedtoprocessmessagesfroma

specificdestination.Intheaboveexample,instancesof

MessageDrivenBean_1processmessagesonlyforDestinationA,

whileinstancesofMessageDrivenBean_2processmessages

onlyforDestinationB.Severalmessagesforthesame

destinationcanbeprocessedatthesametime.If,forexample,



ahundredmessagesforDestinationAarriveatthesametime,

theEJBcontainersimplychoosesahundredinstancesof

MessageDrivenBean_1toprocesstheincomingmessages;each

instanceisassignedamessage.

EJB2.1hasexpandedtheroleofmessage-drivenbeansbeyond

JMSsothattheycansupportothermessagingservicesand

APIs.Thisopensthemessage-drivenbeanuptojustaboutany

kindofresource,includingmessagingsystemsotherthanJMS,

ERPsystemslikeSAP,andlegacysystemslikeIMS.Regardless

ofthetypeofresourcerepresentedbythemessage-driven

bean,theinstancesofthebeantypewillbepooledinthesame

wayastheJMS-MDBs.



3.1.2TheActivationMechanism

Unlikeotherenterprisebeans,statefulsessionbeansmaintain

statebetweenmethodinvocations.Conversationalstate

representsthecontinuingconversationwiththestatefulsession

bean'sclient.Theintegrityofthisconversationalstateneedsto

bemaintainedforthelifeofthebean'sservicetotheclient.

Statefulsessionbeans,unlikestatelesssession,entity,and

message-drivenbeans,donotparticipateininstancepooling.

Instead,statefulsessionbeansuseactivationtoconserve

resources.WhenanEJBserverneedstoconserveresources,it

canevictstatefulsessionbeansfrommemory.Whenabeanis

evicted,itsconversationalstateisserializedtoasecondary

storage.WhenaclientinvokesamethodontheEJBobject,a

newstatefulinstanceisinstantiatedandpopulatedwiththe

statefromtheinitialbean.

Passivationistheactofdisassociatingastatefulbeaninstance

fromitsEJBobjectandsavingitsstate.Passivationrequires

thatthebeaninstance'sstatebeheldrelativetoitsEJBobject.

Afterthebeanhasbeenpassivated,itissafetoremovethe

beaninstancefromtheEJBobjectandevictitfrommemory.



Clientsareunawareofthedeactivationprocess.Rememberthat

theclientusesthebean'sremotereference,whichis

implementedbyanEJBobject,andthereforedoesnotdirectly

communicatewiththebeaninstance.Asaresult,theclient's

connectiontotheEJBobjectcanbemaintainedwhilethebean

ispassivated.

Activatingabeanistheactofrestoringastatefulbean

instance'sstaterelativetoitsEJBobject.Whenamethodon

thepassivatedEJBobjectisinvoked,thecontainer

automaticallycreatesanewinstanceandsetsitsfieldsequalto

thedatastoredduringpassivation.TheEJBobjectcanthen

delegatethemethodinvocationtothebeanasnormal.Figure

3-5showsactivationandpassivationofastatefulbean.In

Figure3-5(a),thebeanisbeingpassivated.Thestateof

instanceBisreadandheldrelativetotheEJBobjectitwas

serving.InFigure3-5(b),thebeanhasbeenpassivatedandits

statepreserved.Here,theEJBobjectisnotassociatedwitha

beaninstance.InFigure3-5(c),thebeanisbeingactivated.A

newinstance,instanceC,hasbeeninstantiatedandassociated

withtheEJBobjectandisintheprocessofhavingitsstate

populatedwiththestateheldrelativetotheEJBobject.



Figure3-5.Thepassivationandactivation

processes



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 3. Resource Management and the Primary Services

Tải bản đầy đủ ngay(0 tr)

×