TheNewJava™ TechnologyMemory

Model java.sun.com/javaone/sf

Jeremy Manson and William Pugh http://www.cs.umd.edu/~pugh

1 |2004JavaOne SM Conference|SessionTS2331 Audience

• Assumeyouarefamiliarwithbasics ofJava ™ technologybasedthreads (“Javathreads”) ─ Creating,startingandjoiningthreads ─ Synchronization ─ wait and notifyAll

2 |2004JavaOne SM Conference|SessionTS2331 JavaThreadSpecification

• RevisedaspartofJSR133

• PartofthenewJavaLanguageSpec ─ andtheVirtualMachineSpec

• Featurestalkedaboutheretodayarein JDK1.5 ─ Notalloftheseideasareguaranteedtoworkin previousversions ─ Previousthreadspecwasbroken ─forbidoptimizationsperformedbymanyJVMs

3 |2004JavaOne SM Conference|SessionTS2331 SafetyIssuesinMultithreaded Systems • Manyintuitiveassumptionsdonothold • Somewidelyusedidiomsarenotsafe ─ OriginalDoublecheckedlockingidiom ─ Checkingnonvolatileflagforthreadtermination • Can’tusetestingtocheckforerrors ─ Someanomalieswilloccuronlyon someplatforms ─e.g.,multiprocessors ─ Anomalieswilloccurrarelyandnonrepeatedly

4 |2004JavaOne SM Conference|SessionTS2331 RevisingtheThreadSpec

• TheJavaThreadSpecificationhasundergone significantrevision ─ Mostlytocorrectlyformalizeexistingbehavior ─ Butafewchangesinbehavior • Goals ─ Clearandeasytounderstand ─ Fosterreliablemultithreadedcode ─ AllowforhighperformanceJVMs • HasaffectedJVMs ─ Andbadlywrittenexistingcode ─IncludingpartsofSun’sJDK

5 |2004JavaOne SM Conference|SessionTS2331 ThisTalk…

• Describebuildingblocksofsynchronization andconcurrentprogramminginJava ─ Bothlanguageprimitivesandutil.concurrent abstractions

• Explainwhatitmeansforcodetobecorrectly synchronized

• Trytoconvinceyouthatcleverreasoning aboutunsynchronizedcodeisalmostcertainly wrong ─ Notneededforefficientandreliableprograms

6 |2004JavaOne SM Conference|SessionTS2331 ThisTalk…

• Wewillbetalkingmostlyabout ─ synchronizedmethodsandblocks ─ volatilefields

• SameprinciplesworkwithJSR166locksand atomicoperations

• Willalsotalkaboutfinalfieldsandimmutability.

7 |2004JavaOne SM Conference|SessionTS2331 Taxonomy

• Highlevelconcurrencyabstractions ─ JSR166andjava.util.concurrent • Lowlevellocking ─ synchronized() blocks • Lowlevelprimitives ─ volatilevariables,java.util.concurrent.atomic classes ─ allowsfornonblockingsynchronization • Dataraces:deliberateundersynchronization ─ Avoid! ─ NotevenDougLeacangetitright

8 |2004JavaOne SM Conference|SessionTS2331 ThreeAspectsof Synchronization • Atomicity ─ Lockingtoobtainmutualexclusion • Visibility ─ Ensuringthatchangestoobjectfieldsmadeinone threadareseeninotherthreads • Ordering ─ Ensuringthatyouaren’tsurprisedbytheorderin whichstatementsareexecuted

9 |2004JavaOne SM Conference|SessionTS2331 Don’tTryToBeTooClever

• Peopleworryaboutthecostofsynchronization ─ Trytodeviseschemestocommunicatebetween threadswithoutusingsynchronization ─locks,volatiles,orotherconcurrencyabstractions • Nearlyimpossibletodocorrectly ─ Interthreadcommunicationwithoutsynchronization isnotintuitive

10 |2004JavaOne SM Conference|SessionTS2331 QuizTime

x = y = 0

Thread1 start threads Thread2 x = 1 y = 1

j = y i = x

Can this result in i = 0 and j = 0 ?

11 |2004JavaOne SM Conference|SessionTS2331 Answer:Yes!

x = y = 0

Thread1 start threads Thread2 x = 1 y = 1

j = y i = x

How can i = 0 and j = 0?

12 |2004JavaOne SM Conference|SessionTS2331 HowCanThisHappen?

• Compilercanreorderstatements ─ Orkeepvaluesinregisters • Processorcanreorderthem • Onmultiprocessor,valuesnotsynchronizedin globalmemory • Thememorymodelisdesignedtoallow aggressiveoptimization ─ includingoptimizationsnoonehasimplementedyet • Goodforperformance ─ badforyourintuitionaboutinsufficiently synchronizedcode

13 |2004JavaOne SM Conference|SessionTS2331 Correctnessand Optimizations • Clevercodethatdependstheorderyouthink thesystem must dothingsinisalmostalways wronginJava • Dekker’s Algorithm(firstcorrect implementation)requiresthisordering ─ doesn’tworkinJava,usesuppliedlocks • Mustusesynchronizationtoenforcevisibility andordering ─ Aswellasmutualexclusion ─ Ifyouusesynchronizationcorrectly,youwillnotbe abletoseereorderings

14 |2004JavaOne SM Conference|SessionTS2331 SynchronizationActions (approximately )

// block until obtain lock synchronized(anObject) { // get main memory value of field1 and field2 int x = anObject.field1; int y = anObject.field2; anObject.field3 = x+y; // commit value of field3 to main memory } // release lock moreCode();

15 |2004JavaOne SM Conference|SessionTS2331 WhenAreActionsVisible toOtherThreads?

Everything before Thread 2 ref1.x = 1 an unlock (release)

lock M lock M

glo = ref1 ref2 = glo

unlock M unlock M

j = ref2.x Thread 1 Is visible to everything after a later lock (acquire) on the same Object

16 |2004JavaOne SM Conference|SessionTS2331 ReleaseandAcquire

• Allaccessesbeforearelease ─ areorderedbeforeandvisibleto ─ anyaccessesafteramatchingacquire

• Unlockingamonitor/lockisarelease ─ thatisacquiredbyanyfollowinglockof that monitor/lock

17 |2004JavaOne SM Conference|SessionTS2331 Ordering

• Roachmotelordering ─ Compiler/processorcanmoveaccessesinto synchronizedblocks ─ Canonlymovethemoutunderspecial circumstances,generallynotobservable

• Somespecialcases: ─ locksonthreadlocalobjectsareanoop ─ reentrantlocksareanoop

18 |2004JavaOne SM Conference|SessionTS2331 Volatilefields

• Ifafieldcouldbesimultaneouslyaccessedbymultiple threads,andatleastoneofthoseaccessesisawrite ─ makethefieldvolatile ─ documentation ─ givesessentialJVMguarantees ─ Canbetrickytogetright,butnearlyimpossiblewithoutvolatile • Whatdoesvolatiledo? ─ readsandwritesgodirectlytomemory ─ notcachedinregisters ─ volatilelongsanddoublesareatomic ─ nottruefornonvolatilelongsanddoubles ─ compilerreorderingofvolatileaccessesisrestricted ─ roachmotelsemanticsforvolatilesandnormals ─ noreorderingforvolatilesandvolatiles

19 |2004JavaOne SM Conference|SessionTS2331 Volatilerelease/acquire

• Avolatilewriteisarelease ─ thatisacquiredbyalaterreadofthesamevariable

• Allaccessesbeforethevolatilewrite ─ areorderedbeforeandvisibletoallaccessesafter thevolatileread

20 |2004JavaOne SM Conference|SessionTS2331 Volatileguaranteesvisibility

• stop must bedeclaredvolatile ─ Otherwise,compilercouldkeepinregister

class Animator implements Runnable { private volatile boolean stop = false; public void stop() { stop = true; } public void run() { while (! stop ) oneStep(); } private void oneStep() { /*...*/ } }

21 |2004JavaOne SM Conference|SessionTS2331 Volatileguaranteesordering

• Ifathreadreads data ,thereisa release/acquireon ready thatguarantees visibilityandordering class Future { private volatile boolean ready ; private Object data; public Object get() { if (!ready) return null; public synchronized return data; void setOnce(Object o) { } if (ready) throw … ; data = o; ready = true; } }

22 |2004JavaOne SM Conference|SessionTS2331 OtherAcquiresand Releases • Otheractionsformrelease/acquirepairs

• Startingathreadisarelease ─ acquiredbytherunmethodofthethread

• Terminationofathreadisarelease ─ acquiredbyanythreadthatjoinswiththe terminatedthread

23 |2004JavaOne SM Conference|SessionTS2331 Defendingagainstdata races

• Attackerscanpassinstancesofyourobjecttoother threadsviaadatarace • Cancauseweirdthingstobeobserved ─ couldbeobservedinsomeJVMs ─ inolderJVMs, String objectsmightbeseentochange ─ changefrom/tmp to/usr • Ifaclassissecuritycritical,musttakesteps • Choices: ─ usesynchronization(eveninconstructor) ─ objectcanbemadevisibletomultiplethreadsbefore constructorfinishes ─ makeobjectimmutablebymakingallfieldsfinal

24 |2004JavaOne SM Conference|SessionTS2331 Immutableclasses

• Makeallcriticalfieldsfinal

• Don’tallowotherthreadstoseeobjectuntilitis fullyconstructed

• JVMwillberesponsibleforensuringthatobject isperceivedasimmutable ─ evenifmaliciouscodeusesdataracestoattackthe class

25 |2004JavaOne SM Conference|SessionTS2331 Optimizationoffinalfields

• Newspecallowsaggressiveoptimizationof finalfields ─ hoistingofreadsoffinalfieldsacross synchronizationandunknownmethodcalls ─ stillmaintainsimmutability

• ShouldallowforfutureJVMs toobtain performanceadvantages

26 |2004JavaOne SM Conference|SessionTS2331 Finalizers

• Onlyguaranteedtoseewritesthatoccurbythe endoftheobject’sconstructor. ─ Iffinalizer needstoseelaterwrites,use synchronization • Fieldsmaybemadefinalearlierthanthe programtextmightimply ─ Synchronizationonobjectalsokeepsitalive • Multiplefinalizers mayberunconcurrently ─ Becarefultosynchronizeproperly!

27 |2004JavaOne SM Conference|SessionTS2331 SynchronizeWhenNeeded

• Placeswherethreadsinteract ─ Needsynchronization ─ Mayneedcarefulthought ─ Mayneeddocumentation ─ Costofrequiredsynchronizationnotsignificant ─Formostapplications ─Noneedtogettricky

28 |2004JavaOne SM Conference|SessionTS2331 SynchronizedClasses

• Someclassesaresynchronized ─ Vector , Hashtable , Stack ─ MostInput/OutputStreams ─ Overheadofunneededsynchronizationcanbe measurable • ContrastwithCollectionclasses ─ Bydefault,notsynchronized ─ Canrequestsynchronizedversion ─ Orcanusejava.util.concurrentversions( Queue , ConcurrentMap implementations) • Usingsynchronizedclasses ─ Oftendoesn’tsufficeforconcurrentinteraction

29 |2004JavaOne SM Conference|SessionTS2331 SynchronizedCollections Aren’tAlwaysEnough • Transactions(DONOTUSE) ─ Violateatomicity…

ID getID(String name) { ID x = h.get(name); if (x == null) { x = new ID(); h.put(name, x); } return x; } • Iterators ─ Can’tmodifycollectionwhileanother threadisiteratingthroughit

30 |2004JavaOne SM Conference|SessionTS2331 ConcurrentInteractions

• Oftenneedentiretransactionstobeatomic ─ ReadingandupdatingaMap ─ WritingarecordtoanOutputStream • OutputStreams aresynchronized ─ Canhavemultiplethreadstryingtowritetothe sameOutputStream ─ Outputfromeachthreadisnondeterministically interleaved ─ Oftenessentiallyuseless

31 |2004JavaOne SM Conference|SessionTS2331 util.concurrent

• Thestuffinjava.util.concurrentisgreat,useit • ConcurrentHashMap hassomeadditional featurestogetaroundproblemswith transactions ─ putIfAbsent ─ concurrentiteration • CopyOnWrite classesallowconcurrent iterationandnonblockingreads ─ modificationisexpensive,shouldberare

32 |2004JavaOne SM Conference|SessionTS2331 DesigningFastCode

• Makeitrightbeforeyoumakeitfast • Reducesynchronizationcosts ─ Avoidsharingmutableobjectsacrossthreads ─ avoidoldCollectionclasses( Vector , Hashtable ) ─ usebulkI/O(or,evenbetter,java.nio classes) • Usejava.util.concurrentclasses ─ designedforspeed,scalabilityandcorrectness • Avoidlockcontention ─ Reducelockscopes ─ Reducelockdurations

33 |2004JavaOne SM Conference|SessionTS2331 ThingsThatDon’tWork

• Thinkingaboutmemorybarriers ─ Thereisnothingthatgivesyoutheeffectofamemorybarrier

• OriginalDoubleCheckIdiom ─ AKAmultithreadedlazyinitialization ─ Anyunsynchronizednonvolatilereads/writesofrefs

• Dependingonsleepforvisibility

• Cleverreasoningaboutcauseandeffectwithrespect todataraces

34 |2004JavaOne SM Conference|SessionTS2331 SynchronizationonThread LocalObjects • Synchronizationonthreadlocalobjects ─ (objectsthatareonlyaccessedbyasinglethread) ─ hasnosemanticsormeaning ─ compilercanremoveit ─ canalsoremovereentrantsynchronization ─e.g.,callingasynchronizedmethodfromanother synchronizedmethodonsameobject

• Thisisanoptimizationpeoplehavetalked aboutforawhile ─ notsureifanyoneisdoingityet

35 |2004JavaOne SM Conference|SessionTS2331 Threadsafelazy initialization

• Wanttoperformlazyinitializationofsomethingthatwill besharedbymanythreads

• Don’twanttopayforsynchronizationafterobjectis initialized

• Standarddoublecheckedlockingdoesn’twork ─ makingthecheckedfieldvolatilefixesit

• Iftwothreadsmightsimultaneouslyaccessafield,and oneofthemwritestoit ─ thefieldmustbevolatile

36 |2004JavaOne SM Conference|SessionTS2331 Wrapup

• Costofsynchronizationoperationscanbesignificant ─ Butcostof needed synchronizationrarelyis

• Threadinteractionneedscarefulthought ─ Butnottooclever ─ Don’twanttohavetothinktohardaboutreordering ─ Nodataracesinyourprogram,noobservablereordering

• Needforinterthreadcommunication...

37 |2004JavaOne SM Conference|SessionTS2331 Wrapup Communication

• Communicationbetweenthreads ─ Requires both threadstointeractvia synchronization

• JSR133&166providenewmechanismsfor communication ─ Highlevelconcurrencyframework ─ volatilefields ─ finalfields

38 |2004JavaOne SM Conference|SessionTS2331 Q&A

39 |2004JavaOne SM Conference|SessionTS2331