Chapter1.ConcurrentObject-Oriented
Programming
Thisbookdiscussessomewaysofthinkingabout,designing,and
implementingconcurrentprogramsintheJava™programming
language. Mostpresentationsinthisbookassumethatyouarean
experienceddeveloperfamiliarwithobject-oriented(OO)programming,
buthavelittleexposuretoconcurrency. Readerswiththeopposite
background—experiencewithconcurrencyinotherlanguages—may
alsofindthisbookuseful.
Thebookisorganizedintofourcoarse-grainedchapters.(Perhapsparts
wouldbeabetterterm.)Thisfirstchapterbeginswithabrieftourofsome
frequentlyusedconstructsandthenbacksuptoestablishaconceptual
basisforconcurrentobject-orientedprogramming:howconcurrencyand
objectsfittogether,howtheresultingdesignforcesimpactconstructionof
classesandcomponents,andhowsomecommondesignpatternscanbe
usedtostructuresolutions.
Thethreesubsequentchaptersarecenteredarounduse(andevasion)of
thethreekindsofconcurrencyconstructsfoundintheJavaprogramming
language:
Exclusion.Maintainingconsistentstatesofobjectsbypreventing
unwantedinterferenceamongconcurrentactivities,oftenusing
synchronizedmethods.
Statedependence.Triggering,preventing,postponing,orrecoveringfrom
actionsdependingonwhetherobjectsareinstatesinwhichtheseactions
couldordidsucceed,sometimesusingmonitormethodsObject.wait,
Object.notify,andObject.notifyAll.
Creatingthreads.Establishingandmanagingconcurrency,using
Threadobjects.
Eachchaptercontainsasequenceofmajorsections,eachonan
independenttopic.Theypresenthigh-leveldesignprinciplesand
strategies,technicaldetailssurroundingconstructs,utilitiesthat
encapsulatecommonusages,andassociateddesignpatternsthataddress
particularconcurrencyproblems.Mostsectionsconcludewithan
annotatedsetoffurtherreadingsprovidingmoreinformationonselected
topics.Theonlinesupplementtothisbookcontainslinkstoadditional
onlineresources,aswellasupdates,errata,andcodeexamples.Itis
accessiblevialinksfrom:
or />Ifyouarealreadyfamiliarwiththebasics,youcanreadthisbookinthe
presentedordertoexploreeachtopicinmoredepth.Butmostreaderswill
wanttoreadthisbookinvariousdifferentorders.Becausemost
concurrencyconceptsandtechniquesinteractwithmostothers,itisnot
alwayspossibletounderstandeachsectionorchapterincomplete
isolationfromalltheothers.However,youcanstilltakeabreadth-first
approach,brieflyscanningeachchapter(includingthisone)before
proceedingwithmoredetailedcoverageofinterest.Manypresentations
laterinthebookcanbeapproachedafterselectivelyreadingthrough
earliermaterialindicatedbyextensivecross-references.
Youcanpracticethisnowbyskimmingthroughthefollowingpreliminaries.
Terminology.ThisbookusesstandardOOterminologicalconventions:
programsdefinemethods(implementingoperations)andfields
(representingattributes)thatholdforallinstances(objects)ofspecified
classes.
InteractionsinOOprogramsnormallyrevolvearoundtheresponsibilities
placeduponaclientobjectneedinganactiontobeperformed,anda
serverobjectcontainingthecodetoperformtheaction.Thetermsclient
andserverareusedhereintheirgenericsenses,notinthespecialized
senseofdistributedclient/serverarchitectures.Aclientisjustanyobject
thatsendsarequesttoanotherobject,andaserverisjustanyobject
receivingsucharequest.Mostobjectsplaytherolesofbothclientsand
servers.Intheusualcasewhereitdoesn'tmatterwhetheranobjectunder
discussionactsasaclientorserverorboth,itisusuallycalledahost;
othersthatitmayinturninteractwithareoftencalledhelpersorpeers.
Also,whendiscussinginvocationsoftheformobj.msg(arg),the
recipient(thatis,theobjectboundtovariableobj)iscalledthetarget
object.
Thisbookgenerallyavoidsdealingwithtransientfactsaboutparticular
classesandpackagesnotdirectlyrelatedtoconcurrency.Anditdoesnot
coverdetailsaboutconcurrencycontrolinspecializedframeworkssuchas
EnterpriseJavaBeans™andServlets.Butitdoessometimesreferto
brandedsoftwareandtrademarkedproductsassociatedwiththeJava™
Platform. Thecopyrightpageofthisbookprovidesmoreinformation.
Codelistings.Mosttechniquesandpatternsinthisbookareillustratedby
variantsofanannoyinglysmallsetoftoyrunningexamples.Thisisnotan
efforttobeboring,buttobeclear.Concurrencyconstructsareoftensubtle
enoughtogetlostinotherwisemeaningfulexamples.Reuseofrunning
examplesmakessmallbutcriticaldifferencesmoreobviousbyhighlighting
themaindesignandimplementationissues.Also,thepresentations
includecodesketchesandfragmentsofclassesthatillustrate
implementationtechniques,butarenotintendedtobecompleteoreven
compilable.Theseclassesareindicatedbyleadingcommentsinthe
listings.
Importstatements,accessqualifiers,andevenmethodsandfieldsare
sometimesomittedfromlistingswhentheycanbeinferredfromcontextor
donotimpactrelevantfunctionality.Theprotectedqualifierisusedasa
defaultfornon-publicfeatureswheneverthereisnoparticularreasonto
restrictsubclassaccess.Thisemphasizesopportunitiesforextensibilityin
concurrentclassdesign(see§1.3.4and§3.3.3). Classesbydefault
havenoaccessqualifier.Samplelistingsaresometimesformattedin
nonstandardwaystokeepthemtogetheronpagesortoemphasizethe
mainconstructionsofinterest.
Thecodeforallexampleclassesinthisbookisavailablefromtheonline
supplement.Mosttechniquesandpatternsinthisbookareillustratedbya
singlecodeexampleshowingtheirmosttypicalforms.Thesupplement
includesadditionalexamplesthatdemonstrateminorvariations,aswellas
somelinkstootherknownusages.Italsoincludessomelargerexamples
thataremoreusefultobrowseandexperimentwithonlinethantoreadas
listings.
Thesupplementprovideslinkstoapackage,util.concurrent,that
containsproduction-qualityversionsofutilityclassesdiscussedinthis
book. ThiscoderunsontheJava2Platformandhasbeentestedwith
1.2.xreleases.Occasionaldiscussions,asides,andfootnotesbriefly
mentionchangesfrompreviousreleases,potentialfuturechangesknown
atthetimeofthiswriting,andafewimplementationquirkstowatchoutfor.
Checktheonlinesupplementforadditionalupdates.
Diagrams.StandardUMLnotationisusedforinteractionandclass
diagrams(seetheFurtherReadingsin§1.1.3).Theaccompanying
diagrams(courtesyofMartinFowler)illustratetheonlyformsusedinthis
book.OtheraspectsofUMLnotation,methodology,andterminologyare
notspecificallyreliedon.
Mostotherdiagramsshowtimethreadsinwhichfree-formgraycurves
tracethreadstraversingthroughcollectionsofobjects.Flattened
arrowheadsrepresentblocking.Objectsaredepictedasovalsthat
sometimesshowselectedinternalfeaturessuchaslocks,fields,andbitsof
code.Thin(usuallylabeled)linesbetweenobjectsrepresentrelations
(normallyreferencesorpotentialcalls)betweenthem.Here'sanotherwise
meaninglessexampleshowingthatthreadAhasacquiredthelockfor
objectX,andisproceedingthroughsomemethodinobjectYthatserves
asahelpertoX.ThreadBismeanwhilesomehowblockedwhileentering
somemethodinobjectX:
<aname="hit8">import
class="docTextHighlight">java</font>.util.Random;
classParticle{</a>
href="height="11"
src="1.1_files/nextmatch.gif"width="17"border="0"/></a>
protectedintx;
protectedinty;
protectedfinalRandomrng=newRandom();
publicParticle(intinitialX,intinitialY){
x=initialX;
y=initialY;
}
publicsynchronizedvoidmove(){
x+=rng.nextInt(10)-5;y+=rng.nextInt(20)-10;}
publicvoiddraw(Graphicsg){
intlx,ly;
synchronized(this){lx=x;ly=y;}
g.drawRect(lx,ly,10,10);}
}
classParticleCanvasextendsCanvas{
privateParticle[]particles=newParticle[0];
ParticleCanvas(intsize){
setSize(newDimension(size,size));}
//intendedtobecalledbyapplet
protectedsynchronizedvoidsetParticles(Particle[]ps){
if(ps==null)
thrownewIllegalArgumentException("Cannotsetnull");
particles=ps;
}
protectedsynchronizedParticle[]getParticles(){
returnparticles;
}
publicvoidpaint(Graphicsg){//overrideCanvas.paintParticle[]ps
=getParticles();
for(inti=0;i
}
}
<aname="hit12">publicinterface
class="docTextHighlight">java</font>.lang.Runnable{</a>
href=" />height="11"src="1.1_files/nextmatch.gif"width="17"border="0"/>
</a>voidrun();
}
publicclassParticleAppletextendsApplet{
protectedThread[]threads=null;//nullwhennotrunning
protectedfinalParticleCanvascanvas
=newParticleCanvas(100);
publicvoidinit(){add(canvas);}
protectedThreadmakeThread(finalParticlep){//utilityRunnable
runloop=newRunnable(){
publicvoidrun(){
try{
for(;;){
p.move();
canvas.repaint();
Thread.sleep(100);//100msecisarbitrary}
}
catch(InterruptedExceptione){return;}
}
};
returnnewThread(runloop);}
publicsynchronizedvoidstart(){
intn=10;//justfordemo
if(threads==null){//bypassifalreadystartedParticle[]particles
=newParticle[n];for(inti=0;i
Particle(50,50);canvas.setParticles(particles);
threads=newThread[n];for(inti=0;i
threads[i]=makeThread(particles[i]);threads[i].start();}
}
}
publicsynchronizedvoidstop(){
if(threads!=null){//bypassifalreadystoppedfor(inti=0;i<
threads.length;++i)threads[i].interrupt();threads=null;
}
}
}
if(Math.random()<0.01)Thread.yield();
OnJVMimplementationsthatemploypre-emptivescheduling
policies,especiallythoseonmultiprocessors,itispossibleandeven
desirablethattheschedulerwillsimplyignorethishintprovidedby
yield.
1.1.2.6ThreadGroups
EveryThreadisconstructedasamemberofaThreadGroup,bydefault
thesamegroupasthatoftheThreadissuingtheconstructorforit.
ThreadGroupsnestinatree-likefashion.Whenanobjectconstructsa
newThreadGroup,itisnestedunderitscurrentgroup.Themethod
getThreadGroupreturnsthegroupofanythread.TheThreadGroup
classinturnsupportsmethodssuchasenumeratethatindicatewhich
threadsarecurrentlyinthegroup.
OnepurposeofclassThreadGroupistosupportsecuritypoliciesthat
dynamicallyrestrictaccesstoThreadoperations;forexample,to
makeitillegaltointerruptathreadthatisnotinyourgroup.Thisis
onepartofasetofprotectivemeasuresagainstproblemsthatcould
occur,forexample,ifanappletweretotrytokillthemainscreen
displayupdatethread.ThreadGroupsmayalsoplaceaceilingonthe
maximumprioritythatanymemberthreadcanpossess.
ThreadGroupstendnottobeuseddirectlyinthread-basedprograms.
Inmostapplications,normalcollectionclasses(forexample
java.util.Vector)arebetterchoicesfortrackinggroupsofThread
objectsforapplication-dependentpurposes.
AmongthefewThreadGroupmethodsthatcommonlycomeintoplay
inconcurrentprogramsismethoduncaughtException,whichis
invokedwhenathreadinagroupterminatesduetoanuncaught
uncheckedexception(forexampleaNullPointerException).This
methodnormallycausesastacktracetobeprinted.
1.1.3FurtherReadings
ThisbookisnotareferencemanualontheJavaprogramming
language.(Itisalsonotexclusivelyahow-totutorialguide,oran
academictextbookonconcurrency,orareportonexperimental
research,orabookondesignmethodologyordesignpatternsor
patternlanguages,butincludesdiscussionsoneachofthesefacetsof
concurrency.)Mostsectionsconcludewithlistsofresourcesthat
providemoreinformationonselectedtopics.Ifyoudoalotof
concurrentprogramming,youwillwanttoreadmoreaboutsomeof
them.
TheJLSshouldbeconsultedformoreauthoritativeaccountsofthe
propertiesofJavaprogramminglanguageconstructssummarizedin
thisbook:
Gosling,James,BillJoy,andGuySteele.TheJava™Language
Specification,Addison-Wesley,1996.Asofthiswriting,asecond
editionofJLSisprojectedtocontainclarificationsandupdatesforthe
Java2Platform.
Introductoryaccountsinclude:Arnold,Ken,andJamesGosling.The
Java™ProgrammingLanguage,SecondEdition,Addison-Wesley,
1998.
Ifyouhaveneverwrittenaprogramusingthreads,youmayfindit
usefultoworkthrougheithertheonlineorbookversionofthe
Threadssectionof:
Campione,Mary,andKathyWalrath.TheJava™Tutorial,Second
Edition,Addison-Wesley,1998.
AconciseguidetoUMLnotationis:Fowler,Martin,withKendall
Scott.UMLDistilled,SecondEdition,Addison-Wesley,1999.The
UMLdiagramkeysonpages3-4ofthepresentbookareexcerptedby
permission.
AmoreextensiveaccountofUMLis:Rumbaugh,James,Ivar
Jacobson,andGradyBooch.TheUnifiedModelingLanguage
ReferenceManual,Addison-Wesley,1999.
1.2ObjectsandConcurrency
Therearemanywaystocharacterizeobjects,concurrency,andtheirrelationships.
sectiondiscussesseveraldifferentperspectives—definitional,system-based,stylistic,
andmodeling-based—thattogetherhelpestablishaconceptualbasisforconcurrent
object-orientedprogramming.
1.2.1Concurrency
Likemostcomputingterms,"concurrency"istrickytopindown.Informally,a
concurrentprogramisonethatdoesmorethanonethingatatime. Forexample,a
webbrowsermaybesimultaneouslyperforminganHTTPGETrequesttogetanHTML
page,playinganaudioclip,displayingthenumberofbytesreceivedofsomeimage,
andengaginginanadvisorydialogwithauser.However,thissimultaneityis
sometimesanillusion.Onsomecomputersystemsthesedifferentactivitiesmight
indeedbeperformedbydifferentCPUs.Butonothersystemstheyareallperformed
asingletime-sharedCPUthatswitchesamongdifferentactivitiesquicklyenoughthat
theyappeartobesimultaneous,oratleastnondeterministicallyinterleaved,tohuman
observers.
Amoreprecise,thoughnotveryinterestingdefinitionofconcurrentprogramming
bephrasedoperationally: AJavavirtualmachineanditsunderlyingoperatingsystem
(OS)providemappingsfromapparentsimultaneitytophysicalparallelism(viamultiple
CPUs),orlackthereof,byallowingindependentactivitiestoproceedinparallelwhen
possibleanddesirable,andotherwisebytime-sharing. Concurrentprogramming
consistsofusingprogrammingconstructsthataremappedinthisway. Concurrent
programmingintheJavaprogramminglanguageentailsusingJavaprogramming
languageconstructstothiseffect,asopposedtosystem-levelconstructsthatareused
tocreatenewoperatingsystemprocesses. Byconvention,thisnotionisfurther
restrictedtoconstructsaffectingasingleJVM,asopposedtodistributed
programming,forexampleusingremotemethodinvocation(RMI),thatinvolves
multipleJVMsresidingonmultiplecomputersystems.
Concurrencyandthereasonsforemployingitarebettercapturedbyconsideringthe
natureofafewcommontypesofconcurrentapplications:
Webservices.Mostsocket-basedwebservices(forexample,HTTPdaemons,servlet
engines,andapplicationservers)aremultithreaded.Usually,themainmotivationfor
supportingmultipleconcurrentconnectionsistoensurethatnewincoming
connectionsdonotneedtowaitoutcompletionofothers. Thisgenerallyminimizes
servicelatenciesandimprovesavailability.
Numbercrunching.Manycomputation-intensivetaskscanbeparallelized,andthus
executemorequicklyifmultipleCPUsarepresent.Herethegoalistomaximize
throughputbyexploitingparallelism.
I/Oprocessing.Evenonanominallysequentialcomputer,devicesthatperformreads
andwritesondisks,wires,etc.,operateindependentlyoftheCPU.Concurrent
programscanusethetimeotherwisewastedwaitingforslowI/O,andcanthusmake
moreefficientuseofacomputer'sresources.
Simulation.Concurrentprogramscansimulatephysicalobjectswithindependent
autonomousbehaviorsthatarehardtocaptureinpurelysequentialprograms.
GUI-basedapplications.Eventhoughmostuserinterfacesareintentionallysinglethreaded,theyoftenestablishorcommunicatewithmultithreadedservices.
Concurrencyenablesusercontrolstostayresponsiveevenduringtime-consuming
actions.
Component-basedsoftware.Large-granularitysoftwarecomponents(forexample
thoseprovidingdesigntoolssuchaslayouteditors)mayinternallyconstructthreadsin
ordertoassistinbookkeeping,providemultimediasupport,achievegreaterautonomy,
orimproveperformance.
Mobilecode.Frameworkssuchasthejava.appletpackageexecutedownloaded
codeinseparatethreadsasonepartofasetofpoliciesthathelptoisolate,monitor,
andcontroltheeffectsofunknowncode.
Embeddedsystems.Mostprogramsrunningonsmalldedicateddevicesperformrealtimecontrol.Multiplecomponentseachcontinuouslyreacttoexternalinputsfrom
sensorsorotherdevices,andproduceexternaloutputsinatimelymanner.Asdefined
inTheJava™LanguageSpecification,theJavaplatformdoesnotsupporthardrealtimecontrolinwhichsystemcorrectnessdependsonactionsbeingperformedby
certaindeadlines. Particularrun-timesystemsmayprovidethestrongerguarantees
requiredinsomesafety-criticalhard-real-timesystems.ButallJVMimplementations
supportsoftreal-timecontrol,inwhichtimelinessandperformanceareconsidered
quality-of-serviceissuesratherthancorrectnessissues(see§1.3.3).Thisreflects
portabilitygoalsthatenabletheJVMtobeimplementedonmodernopportunistic,
multipurposehardwareandsystemsoftware.
1.2.2ConcurrentExecutionConstructs
Threadsareonlyoneofseveralconstructsavailableforconcurrentlyexecutingcode.
Theideaofgeneratinganewactivitycanbemappedtoanyofseveralabstractions
alongagranularitycontinuumreflectingtrade-offsofautonomyversusoverhead.
Thread-baseddesignsdonotalwaysprovidethebestsolutiontoagivenconcurrency
problem.Selectionofoneofthealternativesdiscussedbelowcanprovideeithermore
orlesssecurity,protection,fault-tolerance,andadministrativecontrol,witheithermore
orlessassociatedoverhead.Differencesamongtheseoptions(andtheirassociated
programmingsupportconstructs)impactdesignstrategiesmorethandoanyofthe
detailssurroundingeachone.
1.2.2.1Computersystems
Ifyouhadalargesupplyofcomputersystems,youmightmapeachlogicalunitof
executiontoadifferentcomputer.Eachcomputersystemmaybeauniprocessor,a
multiprocessor,orevenaclusterofmachinesadministeredasasingleunitandsharing
acommonoperatingsystem.Thisprovidesunboundedautonomyandindependence.
Eachsystemcanbeadministeredandcontrolledseparatelyfromalltheothers.
However,constructing,locating,reclaiming,andpassingmessagesamongsuch
entitiescanbeexpensive,opportunitiesforsharinglocalresourcesareeliminated,and
solutionstoproblemssurroundingnaming,security,fault-tolerance,recovery,and
reachabilityareallrelativelyheavyincomparisonwiththoseseeninconcurrent
programs. Sothismappingchoiceistypicallyappliedonlyforthoseaspectsofa
systemthatintrinsicallyrequireadistributedsolution.Andevenhere,allbutthetiniest
embeddedcomputerdeviceshostmorethanoneprocess.
1.2.2.2Processes
Aprocessisanoperating-systemabstractionthatallowsonecomputersystemto
supportmanyunitsofexecution.Eachprocesstypicallyrepresentsaseparaterunning
program;forexample,anexecutingJVM.Likethenotionofa"computersystem",a
"process"isalogicalabstraction,notaphysicalone.So,forexample,bindingsfrom
processestoCPUsmayvarydynamically.
Operatingsystemsguaranteesomedegreeofindependence,lackofinterference,and
securityamongconcurrentlyexecutingprocesses.Processesaregenerallynotallowed
toaccessoneanother'sstoragelocations(althoughthereareusuallysome
exceptions),andmustinsteadcommunicateviainterprocesscommunicationfacilities
suchaspipes.Mostsystemsmakeatleastbest-effortpromisesabouthowprocesses
willbecreatedandscheduled.Thisnearlyalwaysentailspre-emptivetime-slicing—
suspendingprocessesonaperiodicbasistogiveotherprocessesachancetorun.
Theoverheadforcreating,managing,andcommunicatingamongprocessescanbea
lotlowerthaninper-machinesolutions.However,sinceprocessesshareunderlying
computationalresources(CPUs,memory,IOchannels,andsoon),theyareless
autonomous.Forexample,amachinecrashcausedbyoneprocesskillsallprocesses.
1.2.2.3Threads
Threadconstructsofvariousformsmakefurthertrade-offsinautonomy,inpartforthe
sakeofloweroverhead.Themaintrade-offsare:
Sharing.Threadsmayshareaccesstothememory,openfiles,andotherresources
associatedwithasingleprocess.ThreadsintheJavaprogramminglanguagemay
shareallsuchresources. Someoperatingsystemsalsosupportintermediate
constructions,forexample"lightweightprocesses"and"kernelthreads"thatshareonly
someresources,dosoonlyuponexplicitrequest,orimposeotherrestrictions.
Scheduling.Independenceguaranteesmaybeweakenedtosupportcheaper
schedulingpolicies.Atoneextreme,allthreadscanbetreatedtogetherasasinglethreadedprocess,inwhichcasetheymaycooperativelycontendwitheachother
thatonlyonethreadisrunningatatime,withoutgivinganyotherthreadachanceto
rununtilitblocks(see§1.3.2).Attheotherextreme,theunderlyingschedulercan
allowallthreadsinasystemtocontenddirectlywitheachotherviapre-emptive
schedulingrules.ThreadsintheJavaprogramminglanguagemaybescheduled
usinganypolicylyingatoranywherebetweentheseextremes.
Communication.Systemsinteractviacommunicationacrosswiresorwireless
channels,forexampleusingsockets. Processesmayalsocommunicateinthis
fashion,butmayalsouselightermechanismssuchaspipesandinterprocess
signallingfacilities.Threadscanusealloftheseoptions,plusothercheaperstrategies
relyingonaccesstomemorylocationsaccessibleacrossmultiplethreads,and
employingmemory-basedsynchronizationfacilitiessuchaslocksandwaitingand
notificationmechanisms.Theseconstructssupportmoreefficientcommunication,but
sometimesincurtheexpenseofgreatercomplexityandconsequentlygreaterpotential
forprogrammingerror.
1.2.2.4Tasksandlightweightexecutableframeworks
Thetrade-offsmadeinsupportingthreadscoverawiderangeofapplications,butare
notalwaysperfectlymatchedtotheneedsofagivenactivity.Whileperformancedetails
differacrossplatforms,theoverheadincreatingathreadisstillsignificantlygreater
thanthecheapest(butleastindependent)waytoinvokeablockofcode—callingit
directlyinthecurrentthread.
Whenthreadcreationandmanagementoverheadbecomeperformanceconcerns,you
maybeabletomakeadditionaltrade-offsinautonomybycreatingyourownlighterweightexecutionframeworksthatimposefurtherrestrictionsonusage(forexampleby
forbiddinguseofcertainformsofblocking),ormakefewerschedulingguarantees,or
restrictsynchronizationandcommunicationtoamorelimitedsetofchoices.As
discussedin§4.1.4,thesetaskscanthenbemappedtothreadsinaboutthesame
waythatthreadsaremappedtoprocessesandcomputersystems.
Themostfamiliarlightweightexecutableframeworksareevent-basedsystemsand
subsystems(see§1.2.3,§3.6.4,and§4.1),inwhichcallstriggeringconceptually
asynchronousactivitiesaremaintainedaseventsthatmaybequeuedandprocessed
bybackgroundthreads.Severaladditionallightweightexecutableframeworksare
describedinChapter4.Whentheyapply,constructionanduseofsuchframeworkscan
improveboththestructureandperformanceofconcurrentprograms. Theiruse
reducesconcerns(see§1.3.3)thatcanotherwiseinhibittheuseofconcurrent
executiontechniquesforexpressinglogicallyasynchronousactivitiesandlogically
autonomousobjects(see§1.2.4).
1.2.3ConcurrencyandOOProgramming
Objectsandconcurrencyhavebeenlinkedsincetheearliestdaysofeach.Thefirst
concurrentOOprogramminglanguage(createdcirca1966),Simula,wasalso
firstOOlanguage,andwasamongthefirstconcurrentlanguages. Simula'sinitial
OOandconcurrencyconstructsweresomewhatprimitiveandawkward.Forexample,
concurrencywasbasedaroundcoroutines—thread-likeconstructsrequiringthat
programmersexplicitlyhandoffcontrolfromonetasktoanother.Severalother
languagesprovidingbothconcurrencyandOOconstructsfollowed—indeed,even
someoftheearliestprototypeversionsofC++includedafewconcurrency-support
libraryclasses.AndAda(although,initsfirstversions,scarcelyanOOlanguage)
helpedbringconcurrentprogrammingoutfromtheworldofspecialized,low-level
languagesandsystems.
OOdesignplayednopracticalroleinthemultithreadedsystemsprogramming
practicesemerginginthe1970s. Andconcurrencyplayednopracticalroleinthe
wide-scaleembraceofOOprogrammingthatbeganinthe1980s. Butinterestin
OOconcurrencystayedaliveinresearchlaboratoriesandadvanceddevelopment
groups,andhasre-emergedasanessentialaspectofprogramminginpartduetothe
popularityandubiquityoftheJavaplatform.
ConcurrentOOprogrammingsharesmostfeatureswithprogrammingofanykind.
Butitdiffersincriticalwaysfromthekindsofprogrammingyoumaybemostfamiliar
with,asdiscussedbelow.
1.2.3.1SequentialOOprogramming
ConcurrentOOprogramsareoftenstructuredusingthesameprogramming
techniquesanddesignpatternsassequentialOOprograms(seeforexample§1.4
Buttheyareintrinsicallymorecomplex.Whenmorethanoneactivitycanoccurata
time,programexecutionisnecessarilynondeterministic.Codemayexecutein
surprisingorders—anyorderthatisnotexplicitlyruledoutisallowed(see§2.2.7
youcannotalwaysunderstandconcurrentprogramsbysequentiallyreadingthrough
theircode. Forexample,withoutfurtherprecautions,afieldsettoonevalueinone
lineofcodemayhaveadifferentvalue(duetotheactionsofsomeotherconcurrent
activity)bythetimethenextlineofcodeisexecuted. Dealingwiththisandother
formsofinterferenceoftenintroducestheneedforabitmorerigorandamore
conservativeoutlookondesign.
1.2.3.2Event-basedprogramming
Someconcurrentprogrammingtechniqueshavemuchincommonwiththosein
eventframeworksemployedinGUItoolkitssupportedbyjava.awtand
javax.swing,andinotherlanguagessuchasTcl/TkandVisualBasic. InGUI
frameworks,eventssuchasmouseclicksareencapsulatedasEventobjectsthatare
placedinasingleEventQueue.Theseeventsarethendispatchedandprocessed
one-by-oneinasingleeventloop,whichnormallyrunsasaseparatethread.As
discussedin§4.1,thisdesigncanbeextendedtosupportadditionalconcurrencyby
(amongothertactics)creatingmultipleeventloopthreads,eachconcurrently
processingevents,orevendispatchingeacheventinaseparatethread.Again,this
opensupnewdesignpossibilities,butalsointroducesnewconcernsaboutinterference
andcoordinationamongconcurrentactivities.
1.2.3.3Concurrentsystemsprogramming
Object-orientedconcurrentprogrammingdiffersfrommultithreadedsystems
programminginlanguagessuchasCmainlyduetotheencapsulation,modularity,
extensibility,security,andsafetyfeaturesotherwiselackinginC.Additionally,
concurrencysupportisbuiltintotheJavaprogramminglanguage,ratherthan
suppliedbylibraries. Thiseliminatesthepossibilityofsomecommonerrors,and
enablescompilerstoautomaticallyandsafelyperformsomeoptimizationsthatwould
needtobeperformedmanuallyinC.
WhileconcurrencysupportconstructsintheJavaprogramminglanguageare
generallysimilartothoseinthestandardPOSIXpthreadslibraryandrelatedpackages
typicallyusedinC,therearesomeimportantdifferences,especiallyinthedetailsof
waitingandnotification(see§3.2.2). Itisverypossibletouseutilityclassesthatact
almostjustlikePOSIXroutines(see§3.4.4).Butitisoftenmoreproductiveinsteadto
makeminoradjustmentstoexploittheversionsthatthelanguagedirectlysupports.
1.2.3.4Otherconcurrentprogramminglanguages
Essentiallyallconcurrentprogramminglanguagesare,atsomelevel,equivalent,if
onlyinthesensethatallconcurrentlanguagesarewidelybelievednottohavedefined
therightconcurrencyfeatures. However,itisnotallthathardtomakeprogramsin
onelanguagelookalmostequivalenttothoseinotherlanguagesorthoseusingother
constructs,bydevelopingpackages,classes,utilities,tools,andcodingconventions
thatmimicfeaturesbuiltintoothers. Inthecourseofthisbook,constructionsare
introducedthatprovidethecapabilitiesandprogrammingstylesofsemaphore-based
systems(§3.4.1),futures(§4.3.3),barrier-basedparallelism(§4.4.3),CSP(§4.5.1
andothers. Itisaperfectlygreatideatowriteprogramsusingonlyoneofthese
styles,ifthissuitsyourneeds. However,manyconcurrentdesigns,patterns,
frameworks,andsystemshaveeclecticheritagesandstealgoodideasfromanywhere
theycan.
1.2.4ObjectModelsandMappings
ConceptionsofobjectsoftendifferacrosssequentialversusconcurrentOO
programming,andevenacrossdifferentstylesofconcurrentOOprogramming
Contemplationoftheunderlyingobjectmodelsandmappingscanrevealthenatureof
differencesamongprogrammingstyleshintedatintheprevioussection.
Mostpeopleliketothinkofsoftwareobjectsasmodelsofrealobjects,representedwith
somearbitrarydegreeofprecision.Thenotionof"real"isofcourseintheeyeofthe
beholder,andoftenincludesartificesthatmakesenseonlywithintherealmof
computation.
Forasimpleexample,considertheskeletalUMLclassdiagramandcodesketchfor
classWaterTank:
classWaterTank{//Codesketch
finalfloatcapacity;
floatcurrentVolume=0.0f;
WaterTankoverflow;
WaterTank(floatcap){capacity=cap;...}
voidaddWater(floatamount)throwsOverflowException;
voidremoveWater(floatamount)throwsUnderflowException;
}
Theintenthereistorepresent,orsimulate,awatertankwith:
AttributessuchascapacityandcurrentVolume,thatarerepresentedas
fieldsofWaterTankobjects.Wecanchooseonlythoseattributesthatwe
happentocareaboutinsomesetofusagecontexts.Forexample,whileallreal
watertankshavelocations,shapes,colors,andsoon,thisclassonlydeals
volumes.
Invariantstateconstraints,suchasthefactsthatthecurrentVolumealways
remainsbetweenzeroandcapacity,andthatcapacityisnonnegative
neverchangesafterconstruction.
OperationsdescribingbehaviorssuchasthosetoaddWaterand
removeWater.Thischoiceofoperationsagainreflectssomeimplicitdesign
decisionsconcerningaccuracy,granularityandprecision.Forexample,wecould
havechosentomodelwatertanksatthelevelofvalvesandswitches,andcould
havemodeledeachwatermoleculeasanobjectthatchangeslocationasthe
resultoftheassociatedoperations.
Connections(andpotentialconnections)tootherobjectswithwhichobjects
communicate,suchaspipesorothertanks.Forexample,excesswater
encounteredinanaddWateroperationcouldbeshuntedtoanoverflowtank
thatisknownbyeachtank.
Preconditionsandpostconditionsontheeffectsofoperations,suchasrules
statingthatitisimpossibletoremovewaterfromanemptytank,ortoaddwaterto
afulltankthatisnotequippedwithanavailableoverflowtank.
Protocolsconstrainingwhenandhowmessages(operationrequests)are
processed.Forexample,wemayimposearulethatatmostoneaddWater
removeWatermessageisprocessedatanygiventimeor,alternatively,arule
statingthatremoveWatermessagesareallowedinthemidstofaddWater
operations.
1.2.4.1Objectmodels
TheWaterTankclassusesobjectstomodelreality.Objectmodelsproviderulesand
frameworksfordefiningobjectsmoregenerally,covering:
Statics.Thestructureofeachobjectisdescribed(normallyviaaclass)intermsof
internalattributes(state),connectionstootherobjects,local(internal)methods,and
methodsorportsforacceptingmessagesfromotherobjects.
Encapsulation.Objectshavemembranesseparatingtheirinsidesandoutsides.
Internalstatecanbedirectlymodifiedonlybytheobjectitself.(Weignorefornow
languagefeaturesthatallowthisruletobebroken.)
Communication.Objectscommunicateonlyviamessagepassing.Objectsissue
messagesthattriggeractionsinotherobjects.Theformsofthesemessagesmay
rangefromsimpleproceduralcallstothosetransportedviaarbitrarycommunication
protocols.
Identity.Newobjectscanbeconstructedatanytime(subjecttosystemresource
constraints)byanyobject(subjecttoaccesscontrol).Onceconstructed,eachobject
maintainsauniqueidentitythatpersistsoveritslifetime.
Connections.Oneobjectcansendmessagestoothersifitknowstheiridentities.
Somemodelsrelyonchannelidentitiesratherthanorinadditiontoobjectidentities.
Abstractly,achannelisavehicleforpassingmessages.Twoobjectsthatsharea
channelmaypassmessagesthroughthatchannelwithoutknowingeachother's
identities.TypicalOOmodelsandlanguagesrelyonobject-basedprimitivesfordirect
methodinvocations,channel-basedabstractionsforIOandcommunicationacross
wires,andconstructionssuchaseventchannelsthatmaybeviewedfromeither
perspective.
Computation.Objectsmayperformfourbasickindsofcomputation:
Acceptamessage.
Updateinternalstate.
Sendamessage.
Createanewobject.
Thisabstractcharacterizationcanbeinterpretedandrefinedinseveralways.For
example,onewaytoimplementaWaterTankobjectistobuildatinyspecial-purpose
hardwaredevicethatonlymaintainstheindicatedstates,instructions,andconnections.
Butsincethisisnotabookonhardwaredesign,we'llignoresuchoptionsandrestrict
attentiontosoftware-basedalternatives.
1.2.4.2Sequentialmappings
Thefeaturesofanordinarygeneral-purposecomputer(aCPU,abus,somememory,
andsomeIOports)canbeexploitedsothatthiscomputercanpretenditisanyobject,
forexampleaWaterTank.Thiscanbearrangedbyloadingadescriptionof
WaterTanks(viaa.classfile)intoaJVM.TheJVMcanthenconstructapassive
representationofaninstanceandtheninterprettheassociatedoperations.This
mappingstrategyalsoappliesattheleveloftheCPUwhenoperationsarecompiled
intonativecoderatherthaninterpretedasbytecodes.Italsoextendstoprograms
involvingmanyobjectsofdifferentclasses,eachloadedandinstantiatedasneeded,by
havingtheJVMatalltimesrecordtheidentity("this")oftheobjectitiscurrently
simulating.
Inotherwords,theJVMisitselfanobject,althoughaveryspecialonethatcanpretend
itisanyotherobject.(Moreformally,itservesasaUniversalTuringMachine.)While
similarremarksholdforthemappingsusedinmostotherlanguages,Classobjects
andreflectionmakeitsimplertocharacterizereflectiveobjectsthattreatotherobjects
asdata.
Inapurelysequentialenvironment,thisistheendofthestory.Butbeforemovingon,
considertherestrictionsonthegenericobjectmodelimposedbythismapping.Ona
sequentialJVM,itwouldbeimpossibletodirectlysimulatemultipleconcurrent
interactingwaterTankobjects. Andbecauseallmessage-passingisperformedvia
sequentialproceduralinvocation,thereisnoneedforrulesaboutwhethermultiple
messagesmaybeprocessedconcurrently—theyneverareanyway.Thus,sequential
OOprocessinglimitsthekindsofhigh-leveldesignconcernsyouareallowedto
express.
1.2.4.3Activeobjects
Attheotherendofthemappingspectrumareactiveobjectmodels(alsoknownas
actormodels),inwhicheveryobjectisautonomous.Eachmaybeaspowerfulasa
sequentialJVM.Internalclassandobjectrepresentationsmaytakethesameformsas
thoseusedinpassiveframeworks.Forexamplehere,eachwaterTankcouldbe
mappedtoaseparateactiveobjectbyloadinginadescriptiontoaseparateJVM,and
thenforeverallowingittosimulatethedefinedactions.
Activeobjectmodelsformacommonhigh-levelviewofobjectsindistributedobjectorientedsystems:Differentobjectsmayresideondifferentmachines,sothelocation
andadministrativedomainofanobjectareoftenimportantprogrammingissues.
messagepassingisarrangedviaremotecommunication(forexampleviasockets)that
mayobeyanyofanumberofprotocols,includingonewaymessaging(i.e.,messages
thatdonotintrinsicallyrequirereplies),multicasts(simultaneouslysendingthesame
messagetomultiplerecipients),andprocedure-stylerequest-replyexchanges.
Thismodelalsoservesasanobject-orientedviewofmostoperating-system-level
processes,eachofwhichisasindependentof,andsharesasfewresourceswith,other
processesaspossible(see§1.2.2).
1.2.4.4Mixedmodels