<%BANNER%>

Java Memory Model-Aware Model Checking

Permanent Link: http://ufdc.ufl.edu/UFE0044100/00001

Material Information

Title: Java Memory Model-Aware Model Checking
Physical Description: 1 online resource (134 p.)
Language: english
Creator: Jin, Huafeng
Publisher: University of Florida
Place of Publication: Gainesville, Fla.
Publication Date: 2012

Subjects

Subjects / Keywords: benign -- checking -- model
Computer and Information Science and Engineering -- Dissertations, Academic -- UF
Genre: Computer Engineering thesis, Ph.D.
bibliography   ( marcgt )
theses   ( marcgt )
government publication (state, provincial, terriorial, dependent)   ( marcgt )
born-digital   ( sobekcm )
Electronic Thesis or Dissertation

Notes

Abstract: The Java memory model (JMM) determines whether an execution of a concurrent Java program is legal or not. For programs that are data race free, JMM guarantees that all the legal executions are sequentially consistent. For the programs with data races, the legal executions may be sequentially inconsistent, but are still subject to constraints that ensure weak safety properties. Occasionally, one allows programs to contain data races to improve performance. These constraints make it possible, in principle, to reason about the correctness of programs. If the data races do not affect the correctness of the program, we call them benign data races. Model checking is generally applied to determine whether a program meets its specification. But most model checking tools, including Java Pathfinder (JPF), a model checker for Java programs, only generate sequentially consistent executions, but cannot generate executions that are sequentially inconsistent. Therefore they are not sound to reason programs with data races. We give an alternative semantics for the JMM that characterizes the legal executions as a least fixed point and show that this is an overapproximation of the JMM. We have extended Java Pathfinder to generate these executions, yielding a tool, Java PathRelaxer, that can be soundly used to reason about the correctness of programs with data races.
General Note: In the series University of Florida Digital Collections.
General Note: Includes vita.
Bibliography: Includes bibliographical references.
Source of Description: Description based on online resource; title from PDF title page.
Source of Description: This bibliographic record is available under the Creative Commons CC0 public domain dedication. The University of Florida Libraries, as creator of this bibliographic record, has waived all rights to it worldwide under copyright law, including all related and neighboring rights, to the extent allowed by law.
Statement of Responsibility: by Huafeng Jin.
Thesis: Thesis (Ph.D.)--University of Florida, 2012.
Local: Adviser: Sanders, Beverly A.
Local: Co-adviser: Yavuz, Tuba.

Record Information

Source Institution: UFRGP
Rights Management: Applicable rights reserved.
Classification: lcc - LD1780 2012
System ID: UFE0044100:00001

Permanent Link: http://ufdc.ufl.edu/UFE0044100/00001

Material Information

Title: Java Memory Model-Aware Model Checking
Physical Description: 1 online resource (134 p.)
Language: english
Creator: Jin, Huafeng
Publisher: University of Florida
Place of Publication: Gainesville, Fla.
Publication Date: 2012

Subjects

Subjects / Keywords: benign -- checking -- model
Computer and Information Science and Engineering -- Dissertations, Academic -- UF
Genre: Computer Engineering thesis, Ph.D.
bibliography   ( marcgt )
theses   ( marcgt )
government publication (state, provincial, terriorial, dependent)   ( marcgt )
born-digital   ( sobekcm )
Electronic Thesis or Dissertation

Notes

Abstract: The Java memory model (JMM) determines whether an execution of a concurrent Java program is legal or not. For programs that are data race free, JMM guarantees that all the legal executions are sequentially consistent. For the programs with data races, the legal executions may be sequentially inconsistent, but are still subject to constraints that ensure weak safety properties. Occasionally, one allows programs to contain data races to improve performance. These constraints make it possible, in principle, to reason about the correctness of programs. If the data races do not affect the correctness of the program, we call them benign data races. Model checking is generally applied to determine whether a program meets its specification. But most model checking tools, including Java Pathfinder (JPF), a model checker for Java programs, only generate sequentially consistent executions, but cannot generate executions that are sequentially inconsistent. Therefore they are not sound to reason programs with data races. We give an alternative semantics for the JMM that characterizes the legal executions as a least fixed point and show that this is an overapproximation of the JMM. We have extended Java Pathfinder to generate these executions, yielding a tool, Java PathRelaxer, that can be soundly used to reason about the correctness of programs with data races.
General Note: In the series University of Florida Digital Collections.
General Note: Includes vita.
Bibliography: Includes bibliographical references.
Source of Description: Description based on online resource; title from PDF title page.
Source of Description: This bibliographic record is available under the Creative Commons CC0 public domain dedication. The University of Florida Libraries, as creator of this bibliographic record, has waived all rights to it worldwide under copyright law, including all related and neighboring rights, to the extent allowed by law.
Statement of Responsibility: by Huafeng Jin.
Thesis: Thesis (Ph.D.)--University of Florida, 2012.
Local: Adviser: Sanders, Beverly A.
Local: Co-adviser: Yavuz, Tuba.

Record Information

Source Institution: UFRGP
Rights Management: Applicable rights reserved.
Classification: lcc - LD1780 2012
System ID: UFE0044100:00001


This item has the following downloads:


Full Text

PAGE 1

JAVAMEMORYMODEL-AWAREMODELCHECKINGByHUAFENGJINADISSERTATIONPRESENTEDTOTHEGRADUATESCHOOLOFTHEUNIVERSITYOFFLORIDAINPARTIALFULFILLMENTOFTHEREQUIREMENTSFORTHEDEGREEOFDOCTOROFPHILOSOPHYUNIVERSITYOFFLORIDA2012

PAGE 2

c2012HuafengJin 2

PAGE 3

Idedicatethistoeveryonethathelpedmeinthisdissertation. 3

PAGE 4

ACKNOWLEDGMENTS Firstofall,IwouldliketosaythankyoutomyPh.DadvisorDr.BeverlySanders.Itismygreathonortobeherstudent.Duringtheyearsofresearch,shegavemegreatinstructionsonhowtolookforresearchtopics,howtoreadpapers,howtosolveproblems,howtowritegoodacademicliteratures,howtogivepresentations,andhowtocommunicatewithfellowresearchers.Iappreciateallhercontributionsingivingmeresearchinspirations,andopportunitiestoattendacademicconfererences.Mostimportantly,sheprovidedmeanexcellentexampleofrigorouscomputerscientist.Inregardstosoftwaremodelchecking,IwouldliketothankDr.TubaYavuz-Kahveci.Shehelpedmealotinunderstandingthemodelcheckingconcepts.Moreover,sheprovidedmemanypracticaladvicesintheimplementationdetails.Iappreciateallthetimeshespentinmyproject.IwouldalsoliketothankDr.KyungheeKim,theformerPh.DstudentofDr.Sanders.ShesharedherpracticalexperiencewithmeinJavaPathnderwithoutanyreservation.Evenaftergraduation,shecontinuedansweringmyquestionsthroughemail.IalsoappreciateherpreviousworkonJavaRacender(nowjpf-racender).Thistoolisveryhelpfulindeterminingwhetherthelegalexecutionsofaprogramaresequentiallyconsistentornot,andhencemayspeedupthevericationprocess.TheopensourcedtoolprovidedmeagoodexampleonhowtoextendJavaPathnder.FortheJavaPathndertool,IwouldliketothankallthedevelopersfromNASA,especiallyDr.NehaRungta.ThetoolprovidesanimportantwaytoverifyreallifeconcurrentJavaprograms,andgavemeinspirationsinmywork.ForthedetailedJavaPathnderusageissues,IamparticularlyindebtedtoPeterMehlitz,whoisinchargeofJavaPathnderprojects.HeansweredmyquestionswithgreatpatienceintheonlineJPFgroup.IappreciateDr.StephenThebaut'shelpverymuch.Mybasicunderstandingsonsoftwarevalidationandvericationwasacquiredfromhisgraduatelevelcourse 4

PAGE 5

onsoftwaretesting/verication.Heevengavemeanopportunitytobehisteachingassistantinthiscourse,throughwhichIlearnedevenmoreonthissubject.Forthedissertation,IwouldliketothankDr.RandyChowandDr.RickSmith.Theyprovidedmeveryinsightfulsuggestionsduringmyadmissiontocandidacy.Ialsowanttothankallthecommitteemembersintakingtheirtimetoreadmydissertation.IgratefullyacknowledgethedepartmentofComputerandInformationScienceandEngineering.DuringmyPh.Dstudies,Iwasappointedasteachingassistantfor9straightsemestersandreceivedfulltuitionwaiver.ThegenerousnancialsupportfromthedepartmentmademyPh.Dworkpossible.Moreover,beingateachingTA,Ilearnedhowtoexpressideastotheaudienceandhowtohelpthestudents.Iowealottothedepartmentstaffs,JohnBowers,JoanChrisman,ErnestHall,RachelNgai,andformerlyKeriTaylor,CrystalMcJunkin,MattWilliams.Theyhelpedmeagreatdealinthepaperworks,courseregistrations,softwareinstallations,aswellasothereverydaylifeaspects.MygraduatelifeatUniversityofFloridawasenjoyableandunforgetablemostlybecauseofmyfriendsandroommates,XiaochunXu,XiaoLi,YangJiao,XiaoYu,NavyaKooram,MariahGriner,andmanyothers.Iamgratefulforthetimespentwiththem.Lastbutnotleast,IwouldliketosaythankyoutomyparentsfortheircontinuoussupportandencouragementduringmyPh.Dstudies.Mostofall,IappreciatemywifeShan,withouttheloveandsupportfromwhomitisdifcultformetoachievemygoal. 5

PAGE 6

TABLEOFCONTENTS page ACKNOWLEDGMENTS .................................. 4 LISTOFTABLES ...................................... 8 LISTOFFIGURES ..................................... 9 ABSTRACT ......................................... 13 CHAPTER 1INTRODUCTION ................................... 14 2BACKGROUND ................................... 19 2.1MemoryModels ................................ 19 2.1.1Sequentiallyconsistentmemorymodel ................ 19 2.1.2Partialstoreorderandtotalstoreorder ................ 22 2.2TheJavaMemoryModel ........................... 25 2.2.1Well-formedexecution ......................... 28 2.2.2Causalityrules ............................. 30 2.2.3EvaluationofJavamemorymodel .................. 32 2.3DataRaceandProgramCorrectness .................... 34 2.3.1Datarace ................................ 34 2.3.2Programcorrectnessandbenigndatarace ............. 37 2.4ModelChecking ................................ 40 2.4.1Modelcheckingtools .......................... 42 2.4.2JavaPathnder ............................. 42 3THEALGORITHM .................................. 45 3.1AlgorithmOverview .............................. 45 3.2Metadata .................................... 50 3.3FormalDescription ............................... 52 3.4AnExample ................................... 59 4ALGORITHMPROPERTIES ............................ 64 4.1Safety,Completeness,andConvergence .................. 64 4.2Overapproximation ............................... 66 5IMPLEMENTATION ................................. 73 5.1JMMDisambiguation .............................. 73 5.2JPRStructure .................................. 76 5.3JPF-relatedImplementationIssues ...................... 78 5.3.1Bytecode-actiontranslation ...................... 78 6

PAGE 7

5.3.2JPFstaterepresentation ........................ 80 5.3.3Garbagecollection ........................... 81 5.3.4Readingfutureobjects ......................... 82 5.3.5Checkingprogramproperties ..................... 83 5.4Non-JPFImplementationIssues ....................... 85 5.4.1Datatypes ................................ 85 5.4.2Objectandarraycreation ....................... 85 5.4.3Checkinghappens-beforeconsistency ................ 88 5.4.4WorkingwithJavaRacender ..................... 89 6EXPERIENCEANDEVALUATION ......................... 92 6.1TestSuites ................................... 92 6.2PerformanceandEvaluation ......................... 102 6.3ModelCheckingUnderPSO ......................... 110 7RELATEDWORK .................................. 114 8CONCLUSION .................................... 116 APPENDIX AJMMCAUSALITYTESTCASES .......................... 118 BMODELCHECKINGUNDERTSO ......................... 124 REFERENCES ....................................... 126 BIOGRAPHICALSKETCH ................................ 134 7

PAGE 8

LISTOFTABLES Table page 5-1Javabytecode-JMMactionmapping. ........................ 79 5-2DefaultvaluesinJava. ................................ 86 6-1Listofallthepossibleoutcomesoflocalvariablesr1,r2,r3,andr4afterexecution.TranslatedfromthereportschemeofJPR. .................... 105 6-2Latencycomparisononlazy-bbetweennoexplicitsynchronization,AtomicLongarray,andfullysynchronizedmethod. ....................... 109 8

PAGE 9

LISTOFFIGURES Figure page 1-1Memorymodeldeneswhichvalueareadactioncouldsee;Instrictmemorymodels,only2couldbeseen,butinsomeothermemorymodels,either1,2,or3couldbeseenbytheread. .......................... 15 1-2Memorymodelmayprohibitsomecompileroptimizations. ............ 16 2-1SCmemorymodelrestrictsthereorderingofinstructions1and2,or3and4,whicharepairsofindependentinstructionswithinonethread.Sor1==1andr2==2isprohibited. ................................. 20 2-2SCmemorymodelrestrictsredundantreadeliminationofreplacingr5=r1.xwithr5=r2. ...................................... 21 2-3UnderSCmemorymodel,cannotbeprintedout. ............... 21 2-4TSOmemorymodelarchitecture. .......................... 23 2-5Peterson'salgorithmdoesn'tguaranteemutualexclusionunderPSO. ..... 24 2-6PSOallowsmorebehaviorsthanSCmemorymodel:rmayread0,not1. ... 25 2-7hbisatransitiveclosureofswandpo.Wegeta1hba2. ........... 28 2-8UnderJMM,done==true&&r==0isanimpossibleresult. ........... 29 2-9r1==r2==42isanout-of-thin-airresult,andisdisallowedbyJMM. ...... 31 2-10r1==r2==1,r3==0isanout-of-thin-airresult,andisdisallowedbyJMM. .. 32 2-11UnderJMM,r1==r2==r3==1isallowed. .................... 32 2-12Sometimes,theredundantreadeliminationisforbiddenbyJMM. ........ 33 2-13Correctlysynchronized(DRF)program,r1==r2==0istheonlypossibleoutcome. ....................................... 36 2-14Therelationshipbetweenracyprograms,correctprograms,andprogramswithbenigndataraces. ............................... 37 2-15SometimesDRFprogramiserroneous. ...................... 38 2-16Benigndataraceexample:Java'sStringclass.NomatterhowmanythreadsarerunninghashCode()method,thecorrecthashcodewillalwaysbereturned. 39 2-17MultiplethreadsareconcurrentlycallinghashCode().Despitetheexistenceofadatarace,theassertionneverfails. ...................... 39 2-18ModelCheckingStructure. ............................. 40 9

PAGE 10

2-19ModelcheckingprograminFig. 2-1 underSCmemorymodel. ......... 41 3-1Theexecutionsof1strunoftheextendedmodelchecker. ............ 46 3-2Theexecutionsof2ndrunoftheextendedmodelchecker. ............ 46 3-3Ifreadfromfuturewrite,thatwritemustwritethesamevalueasthevalueread. 47 3-4AlgorithmStructure.Aftersomen,WriteSetn)]TJ /F6 7.97 Tf 6.59 0 Td[(1=WriteSetn ........... 48 3-5ThestackstructureofJPFstateexploration.Theshadedblocksrepresentschoicesthathavealreadybeenselected;theemptyblocksrepresentsthecurrentavailablechoices. .............................. 53 3-6JMMAwareJPF,thetoplevelalgorithminJPR. .................. 54 3-7JMMListeneralgorithm ............................... 55 3-8JMMListeneralgorithmcontinuedfromFig. 3-7 ................. 57 3-91stiterationofJPRontheprogramshowninFig. 2-1 .Herethedashedarrowsrepresentdatachoicesandsolidarrowsrepresentthreadchoices. ....... 59 3-10Themetadataofthestatesinthe1stiteration.ThestatenumberiscorrespondingtoFig. 3-9 ...................................... 60 3-112nditerationofJPRontheprogramshowninFig. 2-1 .Herethedashedarrowsrepresentdatachoicesandsolidarrowsrepresentthreadchoices. ....... 62 3-12Themetadataofthestatesinthe2nditeration.ThestatenumberiscorrespondingtoFig. 3-11 ...................................... 62 4-1AlabeledversionofFig. 2-10 .JPRproggeneratesapathwithr1==r2==1&&r3==0.ThisisnotlegalaccordingtoJMM'scausalityrules. ........ 68 4-2ValuepropagationofFig. 4-1 ............................ 69 4-3r1==1&&r2==1&&r3==2isillegalresultbyJMM,butgeneratedbyJPR. .. 70 4-4DataandcontroldependenciesofFig. 4-3 .Herethesolidarrowsshowthedependenciesinthe1stiteration;thedashedarrowsshowadependencyloopformedinthe2nditeration. .............................. 70 4-5RelationshipbetweentheexecutionsgeneratedbyJPRandlegalexecutionsofSCmemorymodel,JMM,andHappens-beforememorymodel. ....... 71 5-1ActionIDexamplesI.Comparisonbetweenscopeandoccurrence. ...... 75 5-2ActionIDexamplesII.r1==r2==1isallowedbyoccurrence-val,butforbiddenbyoccurrence. .................................... 76 10

PAGE 11

5-3TheoverallstructureofJavaPathRelaxer(JPR). ................. 77 5-4JPFGarbageCollection:AfterterminationofThread1,theobjectcreatedbyThread1willnotbeseenbyThread2. ....................... 81 5-5Read`future'object:NullpointerexceptionisthrownwhenThread1readstheobjectthathasnotbeencreatedbyThread2. ................ 82 5-6Inthe2nditeration,theassertionisviolated,butthepathwillalsobediscardedlater,becausetheimposedvalueisnotjustied. ................. 84 5-7ClassDiagramofDataTypes. ............................ 86 5-8Algorithmthathandlesobject/arraycreations,anextensionfromFig. 3-8 ... 87 5-9WorkingwithJRF. .................................. 90 5-10AnotracyvariableunderSCmayberacyundernon-SC. ............ 90 6-1Javacodeoftestcase10from[ 41 ] ......................... 93 6-2RecapofFig. 2-16 .ThedriverclassisshowninFig. 2-17 .Thedataracesarebenignifline 15 isremovedfromtheprogram.Otherwise,theracesarenotbenign. ...................................... 94 6-3Detectprimenumbersbylazyinitializationofpagarray. ............. 95 6-4Calculatingbonaccinumberbylazyinitialization. ................ 96 6-5Programchecksifthereisabadbitinanarray. .................. 97 6-6Doublecheckedlocking ............................... 98 6-7Peterson'salgorithm:guaranteesmutualexclusionunderSC,butfailsunderJMM. ......................................... 99 6-8Dekker'salgorithm:guaranteesmutualexclusionunderSC,butfailsunderJMM. ......................................... 101 6-9ExperimentalresultscomparingtheperformanceofJPRusingActionIDapproachesscope,occurrence,andoccurrence-val,respectively.*meansthatJPRgeneratespathsnotallowedbyJMM. ....................... 102 6-10Javacodeoftestcase11from[ 41 ] ......................... 104 6-11tc6:r1==r2==1isallowedbyJMMaccordingto[ 41 ]. ............. 105 6-12DataandcontroldependenciesofFig. 6-11 .r1==r2==1canbegeneratedbyJPRifscopeactionIDschemeisapplied. ................... 106 6-13Unsafelazyinitialization. ............................... 107 11

PAGE 12

6-14java.util.concurrent.ConcurrentSkipListMap .................... 108 6-15Listener-styledPSOalgorithm. ........................... 113 B-1TSOalgorithmusingJPF .............................. 124 12

PAGE 13

AbstractofdissertationPresentedtotheGraduateSchooloftheUniversityofFloridainPartialFulllmentoftheRequirementsfortheDegreeofDoctorofPhilosophyJAVAMEMORYMODEL-AWAREMODELCHECKINGByHuafengJinMay2012Chair:Dr.BeverlyA.SandersMajor:ComputerandInformationScienceandEngineeringTheJavamemorymodel(JMM)determineswhetheranexecutionofaconcurrentJavaprogramislegalornot.Forprogramsthataredataracefree,JMMguaranteesthatallthelegalexecutionsaresequentiallyconsistent.Fortheprogramswithdataraces,thelegalexecutionsmaybesequentiallyinconsistent,butarestillsubjecttoconstraintsthatensureweaksafetyproperties.Occasionally,oneallowsprogramstocontaindataracestoimproveperformance.Theseconstraintsmakeitpossible,inprinciple,toreasonaboutthecorrectnessofprograms.Ifthedataracesdonotaffectthecorrectnessoftheprogram,wecallthembenigndataraces.Modelcheckingisgenerallyappliedtodeterminewhetheraprogrammeetsitsspecication.Forexample,JavaPathnder(JPF)isamodelcheckerforJavaprograms.However,mostmodelcheckingtools,includingJPF,onlygeneratesequentiallyconsistentexecutions,butnotexecutionsthataresequentiallyinconsistent.Thereforetheyarenotsoundtoreasonaboutprogramswithdataraces.ButoriginalJMMisnotoperationallydenedandisdifculttobeimplementedinmodelcheckers.WegiveanalternativesemanticsfortheJMMthatcharacterizesthelegalexecutionsasaleastxedpointandshowthatthisisanoverapproximationoftheJMM.WehaveextendedJavaPathndertogeneratetheseexecutions,yieldingatool,JavaPathRelaxer,thatcanbesoundlyusedtoreasonaboutthecorrectnessofprogramswithdataraces. 13

PAGE 14

CHAPTER1INTRODUCTIONMostmoderncomputerarchitecturesallowprogramswithmorethanoneconcurrentthread.Thethreadscommunicatewitheachotherbyeithermessagepassingmechanismsorasinglesharedmemoryaddressspace.Theconcurrencyprovideshigherperformancecomparedwithuniprocesscomputers,butalsoraisesmanyissues,bothforprogrammersandforsystemdesigners,especiallywithsharedmemoryarchitectures.Inasharedmemoryarchitecture,multipleprocessesmayaccesstothesameaddressspacesimultaneously.Aparticularquestionthen,iswhenathreadreadsfromaparticularaddress,whichvaluewillitsee?Andoncethatisspecied,whatkindsofoptimizationsandtransformationscanbecarriedoutbytheunderlyingarchitecture(i.e.hardware,compiler)withoutviolatingthisspecication.Toanswerthesequestions,aconceptcalledamemorymodelcameintobeing.Amemorymodeldeneshowmemoryoperationsinaconcurrentprogrammayexecute,orhowprocessesinteractwiththesharedmemory.Inotherwords,itdeter-mineswhatvaluesaprocessmayseewhenreadingfromasharedmemorylocation.Inauniprocessprogram,thereadactionalwaysreturnsthevalueofthelatestwriteactionintheorderspeciedbytheprogram(wecallitprogramorder).Butitismorecomplicatedinconcurrentprogramsbecauseofinterferencefromotherprocesses.Amemorymodelcouldbespeciedattheeitherthehardwareorprogramminglanguagelevels.Atthehardwarelevel,Duboisetal.[ 28 ]discussedmemorymodelonsharedmemorymultiprocessors.AdveandHill[ 1 ]proposedaweaklyorderedhardwarememorymodel.Gharachorloo[ 34 ]speciesamemoryconsistencymodel,processconsistency(PC)modelformultiprocessorarchitectures.TheSPARCmanuals[ 84 85 ]denethreememorymodels,totalstoreorder(TSO),partialstoreorder(PSO),andrelaxedmemoryorder(RMO)forSPARC-V9architectures.Inprogramminglanguagerealms,StarkandBorger[ 86 ]presenteda.NETmemorymodelformultithreadedC# 14

PAGE 15

Initially,x==0Thread1 Thread2 x=1; x=2;r=x; x=3; Figure1-1. Memorymodeldeneswhichvalueareadactioncouldsee;Instrictmemorymodels,only2couldbeseen,butinsomeothermemorymodels,either1,2,or3couldbeseenbytheread. applications.BoehmandAdve[ 12 ]describedaconcurrentC++memorymodel.Battyetal.[ 11 ]establishedamathematicalsemanticsforC++memorymodel.Cohenetal.[ 24 ]cameupwithanefcientmemorymodelforC.Pughetal.initiallypointedoutthefatalawsintheoriginalJavamemorymodelin[ 80 81 ],andMansonetal.[ 59 60 ]proposedanewversionoftheJavamemorymodelwhichhasbeenincludedinJavaLanguageSpecication(JLS)[ 36 ,x17.4].Amemorymodelhasimportantimpactsonbothprogrammersandsystemdesigners.Fromtheprogrammers'pointofview,thememorymodeltellsthemwhichexecutionsarelegalandwhicharenot.Theymayinterpolatethepossibleoutcomesoftheprogrambasedonthememorymodel,throughwhichtheycouldreasonabouttheprogramcorrectnesswithregardtothespecication.SeetheexecutionsequenceofaconcurrentprogramshowninFig. 1-1 ,thememorymodeltellswhichvaluecouldthereadactionsee.Incertainstrictmemorymodels,only2couldbeseen;butinsomeothermemorymodels,either1,2,or3couldbeseenbytheread.Aprogrammaybecorrectunderonememorymodel,butincorrectunderanothermemorymodel.Forexample,thefamousPeterson'salgorithm[ 77 ]whichguaranteesmutualexclusionforconcurrentprogramsundersequentiallyconsistentmemorymodel,failstoprovidemutualexclusionundermanyrelaxedmemorymodelssuchasJMM,TSO,PSO,etc.ThesituationissimilartoDekker'salgorithm[ 27 ,x2.1]. 15

PAGE 16

Initially,x==y==0Thread1 Thread2 r1=x; x=1;r2=x; if(r1==r2) y=1; Figure1-2. Memorymodelmayprohibitsomecompileroptimizations. Systemdesignersapplynumeroushardwareorcompileroptimizationsortransformationstoimprovetheefciencyofthesystem.Memorymodeltellsthemwhichoptimizationsortransformationscanbecarriedoutandwhichcannot.Theyhavetokeepthememorymodelinmindwhendesigningthesystem.SeetheexecutioninFig. 1-2 ,inasingle-threadedprogramwithonlyThread1,aredundantreadeliminationtransformationcouldbeappliedbythecompilertoimprovetheperformance;thesecondreadofxcanbereplacedbyr2=r1,sor2=0.ButwiththeinterferencefromThread2,thisredundantreadeliminationisprohibitedbysomememorymodels,suchasthesequentiallyconsistentmemorymodel,whichonlyallowsareadtoreturnthevalue(1inthiscase)ofthemostrecentwriteinanexecution.Basicallyspeaking,memorymodelservesasabridgebetweenprogrammersandsystemdesigners.Itmustbeeasyenoughfortheprogrammerstounderstand,anditmustalsobenotdifcultforsystemdesignerstocomplywithwhendesigningunderlyingarchitectures.Memorymodelsshouldstrikethebalancebetweenthesetwoaspects.Typically,strictmemorymodelsareeasiertounderstandbutdifculttoimplement,whilerelaxedmemorymodelsarejusttheopposite.Amongthose,thesimplest,andmostcommonlyassumedmemorymodelissequentiallyconsistent(SC)memorymodel[ 51 ],inwhichreadactionscanonlyreturnthevalueofthemostrecentwriteactionalongacertainexecutionpath.SCmemorymodeliseasytounderstandbyprogrammers;onlytheinterleavingsofinstructionsareconsidered,otherwisejusttreatasasequentialprogram.SCmemorymodelhas 16

PAGE 17

longbeentheimplicitunderlyingassumptionformostconcurrentprogramanalyzers,suchasSPIN[ 73 ]andJavaPathnder(JPF)[ 42 ].However,SCmemorymodelhasmanylimitations.Itrestrictsmanyverycommonoptimizationsandtransformationsthatarecarriedoutbymodernhardwareorcompilers,aswesawinFig. 1-2 .Therefore,SCmemorymodelisdifculttoimplementinreality.Toimprovetheexecutionperformance,relaxedmemorymodelsareproposed.ThePSO,TSO,partialstoreloadorder(PSLO)[ 5 ],properlylabeled(PL)model[ 34 ],data-race-free(DRF)memorymodel[ 1 ],C#memorymodel,andJMMarerelaxedmemorymodels.Relaxedmemorymodelsallowcompileroptimizationsandtransformationsincertaindegrees,andthusmorebehaviorsarepossible.Typically,ifamemorymodelM1ismorerelaxedthanM2,thenmorebehaviorsareallowedbyM1aremorethanallowedbyM2.Acomparisonbetweenmemorymodelscanbefoundat[ 82 ].TheJavamemorymodelistherstcompleteandwidelyacceptedrelaxedmemorymodelforhigh-levelprogramminglanguages.Itisrelaxed,whichmeansitallowssomeoptimizationsandtransformationsfromcompilers.Italsoprovidessomeconstraintsonthebehaviorofprogramswithdataraces.TheJMMguaranteessequentialconsistencyonlyiftheprogramisdata-race-free.JMMisverycomprehensivebutitisstillnotperfect.Firstly,itstillprohibitscertainkindsofcompilertransformations[ 92 ].Moreimportantly,itisdeclarativelyandnon-operationallydened,andisnotstraightforwardtounderstand.TobetterunderstandJMMandreasoningaboutprogramswithdataracesunderJMM,toolsupportisdesirable.WedescribeaJMM-awaremodelchecker,JavaPathRelaxer(JPR),whichisanextensionofJavaPathnder[ 42 91 ]andgeneratesallofthelegalexecutionsofniteJavaprogramswithdataracessothattheirpropertiescanbeveried.ThewaytheJMMdeneslegalexecutionsinprogramswithdataracesdoesnotlenditselftopreciseimplementationwithamodelcheckerandhasbeenshown[ 92 ] 17

PAGE 18

tobestricterthanthedesignersintended.Weuseanalternateapproach.InsteadofdeningalegalexecutionbytheexistenceofasequenceofjustifyingexecutionsastheJMMdoes,wecomputeasetofpathsthatistheleastxedpointofamonotonefunction.WeshowthatthesetofpathsgeneratedbyJPRisanoverapproximationofthesetoflegalexecutions.AlthoughthedetailsoftheformalizationandimplementationofJPRarespecicforJava,themainideasareapplicabletootherlanguageswithamemorymodelbasedonthehappens-beforerelation.Themaincontributionsofthisworkare Anew,xed-pointbased,approachtothecharacterizationoflegalexecutionsforrelaxedmemorymodels. Atool,JPRthatgeneratesallofthelegalexecutionsaccordingtothexed-pointcharacterization. Aproofthatthexed-pointbasedapproachisanoverapproximationoftheJMM,andthusJPRissoundforJavaprogramswithdataraces. InsightsintohowtheJMMmaps(ordoesnotmap)intoprogramconstructs.Therestofthethesisisorganizedasfollows:Chapter2introducessomeusefultheoreticalbackgrounds,somewell-knownmemorymodels,theformaldenitionofJMM,therelationshipbetweendataraceandprogramcorrectness,andmodelchecking.Chapter3describesthecorealgorithmofJPRindetail.Chapter4formallyprovesthatthealgorithmgeneratesanoverapproximationofJMM.Chapter5presentstheimplementationissuesrelatedtoJPR.Chapter6summarizestheexperimentalresultsanddiscussesthepossibleextensionoftheideaontootherrelaxedmemorymodels.Chapter7listssomeoftherelatedworks.Finally,Chapter8givesaconclusion. 18

PAGE 19

CHAPTER2BACKGROUNDThischapterintroducessometheoriesandtechnologiesusedinthework.BeforedippingintothedetailsofJavamemorymodel,werstlyintroducesomeofthewell-knownmemorymodels;aneasybutstrictmemorymodel,SCmemorymodel,andtwootherrelaxedmemorymodels,PSOandTSO.AftertheformaldescriptionofJavamemorymodel,wediscusstherelationshipbetweendataraceandprogramcorrectness.Finally,wetalkaboutmodelcheckingandJavaPathndertool,whichisbasisforJPR. 2.1MemoryModelsAsdiscussedinChapter1,amemorymodeldeneshowprocessesorthreadsinteractwiththesharedmemory.Itdetermineswhichvaluedoesagivenreadactionmayseeinanexecution.Inthissection,werstintroducethewidelyknownSCmemorymodel;thentalkabouttworelaxedstorebuffer-basedmemorymodels,PSOandTSO.Withthesememorymodelsinmind,itwouldbeeasiertounderstandJMM. 2.1.1SequentiallyconsistentmemorymodelSequentiallyconsistentmemorymodelwasrstraisedbyLamportin1979.InSCmemorymodel,theresultofanexecutionisthesameasiftheoperationshadbeenexecutedintheorderspeciedbytheprogram,andtheoperationsofeachindividualprocessorappearinthissequenceintheorderspeciedbyitsprogram[ 51 ].ThismeansthatunderSCmemorymodel,theactionsmustappearoneatatime,andinsometotalorderwhichisconsistentwiththeprogramorder.Inanexecutionsequence,areadactiontoasharedmemorylocationonlyseesthevaluewrittenbythemostrecentwriteactiontothesamememorylocationinthatsequence.UnderSCmemorymodel,programmersonlyneedtoconsiderinstructioninterleaving.Let'sseetheexecutionsequenceshowninFig. 1-1 ,theactionsappearoneatatime,andthereadactionseesthemostrecentwrite,sothereadofxinThread1 19

PAGE 20

Initially,x==y==0Thread1 Thread2 1r2=x; 3r1=y;2y=1; 4x=2; Figure2-1. SCmemorymodelrestrictsthereorderingofinstructions1and2,or3and4,whicharepairsofindependentinstructionswithinonethread.Sor1==1andr2==2isprohibited. canonlysee2becausethewriteof2fromThread2isthemostrecentwriteactioninthesequence.Itcannotseeeither1or3.SCmemorymodeliseasyforprogrammerstounderstand.Givenanexecutionsequenceofaprogram,theycanonlygetoneoutcome.Also,sometimesprogrammersdon'tneedtouseexplicitsynchronizationmechanismslikelockstoguaranteemutualexclusion,suchasPeterson'salgorithm.AlthoughSCmemorymodelisanintuitivemodel,itrestrictsmanycommonoptimizationsandtransformationsfrombothhardwareandcompiler.Reorderingofmemoryoperationsiscommonforcompilers.Thismaybearesultofvaluecaching,sub-expressionelimination,etc.ButSCmemorymodelprohibitsanykindofreorderingofmemoryoperationstosharedlocations,eveniftheoperationshavenocontroldependenciesnordatadependencies.ConsiderthesimpleexampleshowninFig. 2-1 [ 60 ].Lines1and2fromThread1,aswellaslines3and4fromThread2,havenodatanorcontroldependencies,sotheymightbeswitchedbythecompiler.Inthatcase,r2==2andr1==1isapossibleoutcome.Butinanysequentiallyconsistenttraces,thisresultisforbidden.Wecannotndatotalorderofinterleavedinstructionsthatisconsistentwithprogramordertojustifythisresult.Anothercompileroptimization,redundantreadelimination,whichcanbeviewedasreordering,isalsoprohibitedbySCmemorymodel.ConsidertheexampleshowninFig. 2-2 [ 36 ,x17.3].Inanysequentiallyconsistenttrace,dependingonhowthethreadsinterleave,thexeldofthesingleobjectinvolvedwouldchangefrom0to3atsome 20

PAGE 21

Initiallyp==q,p.x==0Thread1 Thread2 r1=p; r6=p;r2=r1.x; r6.x=3;r3=q r4=r3.x r5=r1.x Figure2-2. SCmemorymodelrestrictsredundantreadeliminationofreplacingr5=r1.xwithr5=r2. Initiallyx==y==0Thread1 Thread2 x=1; if(x==1)fif(y==1) x=0;printx; y=1; g Figure2-3. UnderSCmemorymodel,cannotbeprintedout. pointandthenremain3thereafter.Ifweapplyaredundantreadeliminationontheprogram,replacingthelastreadr1.xinThread1withr5=r2.Thenthevalueofr1.xwouldchangefrom0to3andthenbackto0.Butsuchatraceisnotsequentiallyconsistent.Seeanotherexample(Fig. 2-3 [ 92 ]),underSCmemorymodel,theprogramcanneverprintout.Becauseiftheprinteverexecutes,thelatestwritetoxisx=0.Howevermoderncompilersmaytreatthereadintheprintxasaredundantreadandreplaceitwithprint1.Therestrictionofcommoncompileroptimizations/transformationsisamajordrawbackofSCmemorymodel.TheimplementationofSCmemorymodelisveryexpensive.Thissignicantlyaffectstheperformanceofprogramexecution.Toovercomethisdrawback,relaxedmemorymodelsareproposed,suchasweakorderingmodelin[ 1 ],releaseconsistencymodelin[ 34 ],locationconsistencymodelin[ 33 ],partialstoreorder(PSO)andtotalstoreorder(TSO)[ 85 ].Relaxedmemorymodelallows 21

PAGE 22

morecompileroptimizationsandtransformations.Thememorymodelsforhighlevelprogramminglanguages(Java,C,C++,C#)areallrelaxed. 2.1.2PartialstoreorderandtotalstoreorderPartialstoreorder(PSO)andtotalstoreorder(TSO)aretwoofthethreememorymodelsforSPARCarchitectures[ 85 ](TSOisalsosupportedbyX86processors[ 75 ]).Bothofthemarebasedonstorebuffers.TheyallowmorehardwareoptimizationsthanSCmemorymodel,andarehencerelaxedmemorymodels.Instorebufferbasedmemorymodels,eachprocessisassociatedwithalistofrst-in-rst-out(FIFO)buffers(calledstorebuffers).Thewriteactiondoesnotwritedirectlytothesharedmemorylocation,butinsteadwritestothecorrespondingstorebuffersassociatedwiththeprocess.Thisphaseiscalledstore.Aftersomenon-deterministictime,aseparateushphasecommitsthevaluesinastorebuffertothemainmemoryinanFIFOmanner.Thereadaction(calledload),ontheotherhand,retrievesvaluefromthestorebufferbeforereferringtothemainmemory.TheTSOmemorymodelarchitectureisshowninFig. 2-4 (derivedfrom[ 84 ,xK.2]).EachprocessisassociatedwithanFIFOstorebuffer.Thestoreoperationputsthevalueintothestorebuffer.Thevaluesinthestorebufferareeventuallyushedtothesharedmainmemoryinthesameorderastheywereputinthebuffer.Theloadoperationgetsthemostrecentvaluefromthestorebufferofthecorrespondingprocess.Ifthevaluedoesn'texist,itthenaccessesthemainmemorytogetthevalue.ThePSOmemorymodelissimilartoTSObutperformance-enhanced.InPSO,eachprocessmaintainsasetofFIFOstorebuffers,witheachstorebufferassociatedtoamemorylocation.Ifweusepitodescribeprocess,xtodenotevariables,andvtodenoteavalue,thenaninformaloperationalsemanticsofPSOmemorymodelisasfollows: store(pi,x,v):putvtothestorebufferassociatedwithpiandx load(pi,x):getthelatestvaluefromthestorebufferassociatedwithpiandx,ifitisemptythengetthevalueofxfromthemainmemory. 22

PAGE 23

Process1 Process2 Processn MainMemory ?store ?store ?storeaaaaaaaaaaaaaAAAAA!!!!!!!!!!!!! load load -loadFIFOstorebuersFigure2-4. TSOmemorymodelarchitecture. ush(pi,x):committheoldestvalueofstorebufferassociatedwithpiandxtothemainmemoryandremoveitfromthestorebuffer.Besidesstore,load,andush,processorsalsoprovideafenceinstructiontoallowprogrammerstoenforceorderingofmemoryoperations.Thestrongestfencecanbeviewedas: fence(pi):foreachstorebufferofpi,ifitisnotempty,forceushingfromstorebuffertothemainmemory.Withtheoperationalsemantics,PSOmemorymodelguaranteesthefollowingpartial-coherenceproperties[ 50 ]: Intra-processcoherence:Aprocessshouldonlyseethemostup-to-datevaluewrittenbyitselftoavariable. Inter-processcoherence:Aprocessshouldseethevalueswrittenbyanotherprocessintheordertheywerewritten. 23

PAGE 24

Process0 Process1 while(true)f while(true)fstoreent0=true; storeent1=true;storeturn=1; storeturn=0;dof dofloade=ent1; loade=ent0;loadt=turn; loadt=turn;gwhile(e==true&&t==1); gwhile(e==true&&t==0);//CriticalSection //CriticalSectionstoreent0=false; storeent1=false;g g Figure2-5. Peterson'salgorithmdoesn'tguaranteemutualexclusionunderPSO. Fencecoherence:Afencewritesthemostup-to-datevalueswrittenbytheprocesstothemainmemory.PSOandTSOmemorymodelshavelessstrictsemanticsthanSCmemorymodel.Becauseofthestorebuffers,thevaluewrittenbyaprocessmaynotbeinstantlyvisibletootherprocesses.Areadactionmayseeanoldvalueratherthantheup-to-datevalue.SoforFig. 1-1 ,thereadmayseeeither1or2.AndtheredundantreadeliminationinFig. 2-3 isallowed.StorebuffermemorymodelsallowmoreoptimizationsthanSCmemorymodel,butsomeprogramsthatworkneunderSCmemorymodelnowhaveproblems.SeethePeterson'sAlgorithmwithexplicitmemoryoperationsshowninFig. 2-5 [ 50 ],itguaranteesmutualexclusionunderSCmemorymodel.Whenaprocessisenteringthecriticalsection,itloopsoveruntiltheentvalueoftheotherprocessisfalse,sothatthetwoprocessescannotaccessthecriticalsectionatthesametime.ButunderPSO,thealgorithmdoesn'tguaranteethisproperty;inthepresenceofthestorebuffer,theloadforentoftheotherprocessmaynotreturnthemostrecentvalue,sobothprocessesmayenteratthesametime.TomakePeterson'sAlgorithmworkcorrectlyunderPSO,certainfenceoperations(i.e.forceushofstorebuffers)shouldbeinsertedafterappropriateposition. 24

PAGE 25

Initially,x==0,done==falseThread1 Thread2 x=1; while(!done)f/*spin*/gdone=true; r=x; Figure2-6. PSOallowsmorebehaviorsthanSCmemorymodel:rmayread0,not1. AlsolookattheexampleshowninFig. 2-6 ,underSCmemorymodel,ifthereadinThread2everexecutes,itcanonlyread1.ButunderPSO,thevalue1inThread1maybewrittentothestorebuffer,notthememory,soThread2mayreadtheoldvalue0instead.AlthoughPSOandTSOaremorerelaxedthanSCmemorymodel,somecommonoptimizationsarestillrestricted.ThereorderingmentionedinFig. 2-1 isnotpermitted.Inanyexecutionsequence,wecannotgetr1==1&&r2==2.Alsovalue3cannotbeseenbythereadinFig. 1-1 2.2TheJavaMemoryModelJavamemorymodel(JMM)servesasthecoreconceptofthiswork.JMMisarelaxedmemorymodelforJava.Itistherstattempttoformalizeamemorymodelforhighlevellanguages.JMMhasencouragedotherhighlevellanguages,suchasC++andC#,todesigntheirownmemorymodels.Italsohasgreatimpactonhardware[ 64 ].JMMallowsmanycommonoptimizationsandtransformations.Sequentialconsistencyisnotalwaysguaranteedintheexecutions.ButJMMprovidesasequentialconsistencyguaranteeforprogramsthatarecorrectlysynchronized,i.e.programswithoutdataraces(data-race-freeprograms,orDRFprograms).JMMisbasedonthedenitionofwell-formedexecution.TodeterminewhetheranexecutionislegalunderJMM,wemustrstensurethatitiswell-formed.Thesecondstepistoapplythenon-operationalcausalityrequirementrulestojustifytheexecution.IftheexecutioncanbejustiedbyJMM'scausalityrules,thenitisJMMlegal.Well-formedexecutionguaranteesbasicintra-andinter-threadconsistencies,andcausalityrules 25

PAGE 26

aredesignedtoruleoutout-of-thin-airresults.Here,causalmeansdataandcontroldependencycauses.BelowisabriefoverviewoftheformaldenitionoftheJavamemorymodel.Thedetailedspecicationisgivenin[ 36 60 ].Wewillfollowabriefversiondescribedin[ 7 ]1.AnactioninJavamemorymodelisamemory-relatedoperationthatbelongstoathread.Theformaldenitionofactionis: Denition1(Action). Anactionaisrepresentedbyatupleht,k,v,ui,where trepresentsthethreadthattheactionbelongsto krepresentsthekindoftheaction vrepresentsthememorylocation(variableormonitor)involvedintheaction uisanarbitraryuniqueidentierfortheactionHeretheactionkindcouldbeeithervolatile2read,volatilewrite,non-volatileread,non-volatilewrite,lock,unlock,andspecialsynchronizationactionssuchasthreadstart,threadterminationdetection,etc.Alltheactionsexceptfornon-volatilereadandwritearecalledsynchronizationactions. Denition2(Execution). AnexecutionEisdescribedbyatuplehA,P,po,so,W,Viwhere Aisanitesetofactions. Pisaprogram. 1Themostimportantdifferencesbetween[ 60 ]and[ 7 ]arethatthelatterrequiresthatthetotalorderforSCexecutionsbeconsistentwithboththesynchronizationorderandprogramorder(asopposedtojusttheprogramorder,correctinganapparentoversightintheJMMformulation),formulatesthesemanticsintermsofniteexecutions,andignoresexternalactions.2InJava,variablesdeclaredwithvolatilekeyword[ 36 ,x8.3.1.4]areensuredformutualexclusion.Writestovolatilevariablesguaranteesvisibility,i.e.areadactionperformedonvolatilevariablesalwaysseethevaluewrittenbythemostup-to-datewriteaction. 26

PAGE 27

po,theprogramorder,isapartialorderonAobtainedbytakingtheunionoftotalordersrepresentingeachthread'ssequentialsemantics. so,thesynchronizationorder,isatotalorderoverallofthesynchronizationactionsinsetA. W,thewrite-seenfunction,assignsawriteactiontoeachreadaction.Itreectsthewriteseenbyaread. V,thevaluewrittenfunction,assignsavaluetoeachwrite.WithVandW,wecanobtainthevalueseenbyareadbycallingV(W(r)).Thesynchronizes-withorder(sw)isapartialorderthatrelatescertainpairsofsynchronizationactioninA.Forsynchronizes-withordera1swa2,wecategorizea1(thesource)asreleaseaction,anda2(destination)asacquireaction.Thisisapartiallistofsynchronizes-withrelationsfrom[ 36 ,x17.4.4]: Anunlockactiononmsynchronizes-withallsubsequentlockactionsonm.3 Awritetovolatilevariablevsynchronizes-withallsubsequentreadactionsonv. Athreadstartactionsynchronizes-withtherstactionofthestartedthread. Thewritetothedefaultvalue(i.e.0,false,null)tothevariablesynchronizes-withtherstactionofeachthread. ThenalactioninthreadT1synchronizes-withanyactioninanotherthreadT2thatdetectsT1hasterminated. IfthreadT1interruptsthreadT2,theinterruptsynchronizes-withanypointwhereanyotherthreaddeterminesT2hasbeeninterrupted.Thehappens-beforeorderhbisatransitiveclosureofsynchronizes-withorderandprogramorder.Formallyitis:hb=(sw[po)+.ConsidertheexecutionsequenceshowninFig. 2-7 ,accordingtotheorderspeciedbytheprogram,wegettheprogramorder:a1porelease(m)andacquire(m)poa2;thesynchronizes-withorderdenes 3Here,subsequentisdenedaccordingtothesynchronizationorder. 27

PAGE 28

Thread1Thread2a1release(m)acquire(m)a2 ? ?poposw hbFigure2-7. hbisatransitiveclosureofswandpo.Wegeta1hba2. release(m)swacquire(m),sobecauseofthetransitiveclosureofhappens-before,wegeta1hba2. 2.2.1Well-formedexecutionJMM'swell-formedexecutionsatisestypesafetyandsomeunsurprisingconsistencyrequirementsonthevariouspartialandtotalorders.Thetwomostimportantrulesforourpurposesareintra-threadconsistencyandhappens-beforeconsistency. Denition3(Well-formedexecution). See[ 7 ,Denition6]forthecompletedenition. 1. Aisnite. 2. poisatotalorderoveractionsinonethread. 3. soisatotalorderoversynchronizationsinA. 4. soisconsistentwithpo. 5. Wisproperlytyped. 6. Lockingisproper:numberoflocksisthesameasnumberofunlocks. 7. Intra-threadConsistency:Programorderisintra-threadconsistent.Foreachthreadt,thesequenceofactionkindsandvaluesofactionsperformedbytintheprogramorderpoissequentiallyvalid4withrespecttoPandt. 4Sequentialvalidityessentiallymeansthatgiventhevaluesobtainedwhenavariableisread,eachthreadobeystheJavalanguagesemantics. 28

PAGE 29

L0.x=0,done=false;(doneisvolatile)L1.x=1;L2.done=true;L3.while(done)f/*spin*/gL4.r=x;AAAAAAAAU ? ?XXXXXXzFigure2-8. UnderJMM,done==true&&r==0isanimpossibleresult. 8. SynchronizationOrderConsistency:soisconsistentwithW:Foranyvolatilereadactionr,W(r)sorandforanyvolatilewritewsuchthatw.v=r.v,eitherwsoW(r)orrsow. 9. Happens-beforeConsistency:hbisconsistentwithW:foranyreadrofvariablev, r6hbW(r) thereisnointerveningwritewtov,i.e.ifW(r)hbwhbrandwwritestovthenW(r)=w.Amongthewell-formedexecutionrules,Rule 9 ,thehappens-beforeconsistencyisthemostimportantrule,othersareobvious.Itforbidsanon-volatilereadtoseeawriteonthesamevariablethathappensafterit.Anditalsoforbidsanon-volatilereadtoseeawriteonthesamevariablethatishappens-beforeitbutwithaninterleavingwriteinbetweenthem.Let'slookattheexampleshowninFig. 2-6 ,supposedoneisvolatile,thenifthereadinThread2everexecutes,theexecutionsequenceisFig. 2-8 .Inthegure,happens-beforeedgesareshown.Accordingtothesynchronizes-withrelationruleslistedin[ 36 ,x17.4.4],thewritingtothedefaultvalueshappens-beforetherstactionineachthread;andthereishappens-beforerelationfromthevolatilewriteinThread1tothevolatilereadinThread2.Inthistrace,ifW(L4)=L0(i.e.r==0),thenonthepathL0!L1!L2!L3!L4,wehaveW(L4)hbL1hbL4,whereL1isalso 29

PAGE 30

awritetothesamevariablex.ThisviolatesRule 9 ofDenition 3 .Sothisexecutionisnotwell-formed. 2.2.2CausalityrulesInadditiontothewell-formedexecutionconcept,JMMprovidesCausalityRequire-mentsorLegality.Thisistoruleoutout-of-thin-airresults.Theideaisthatawell-formedexecutionEislegalifthereis(roughlyspeaking)asequenceofwell-formedexecutionsEiwithactionsetsAiandasubsetofactionsCicalledthecommitsetwhereeachcommittedreadeitherseesacommittedwriteorawritethathappens-beforeit.ItisrequiredthatCi)]TJ /F7 7.97 Tf 6.58 0 Td[(1CiandthatthesequenceeventuallyproducesEwithallofitsactionscommitted. Denition4(LegalExecution). [ 7 ,Denition7]5of[ 60 ,x5.4].Awell-formedexecutionE=hA,P,po,so,W,Viwithhappens-beforeorderhbislegalifthereisanitesequenceofsetsofactionsCiandwell-formedexecutionsEi=hAi,P,poi,soi,Wi,Viiwithhappens-beforeorderhbisuchthatC0=,Ci)]TJ /F7 7.97 Tf 6.59 0 Td[(1Ciforalli>0,SCi=A,andforeachi>0,thefollowingaresatised: 1. CiAi 2. hbijCi=hbjCi 3. soijCi=sojCi 4. VijCi=VjCi 5. WijCi)]TJ /F17 5.978 Tf 5.75 0 Td[(1=WjCi)]TJ /F17 5.978 Tf 5.75 0 Td[(1 6. Forallreadsr2Ai)]TJ /F3 11.955 Tf 11.96 0 Td[(Ci,Wi(r)hbir 7. Forallreadsr2Ci)]TJ /F3 11.955 Tf 11.96 0 Td[(Ci)]TJ /F7 7.97 Tf 6.58 0 Td[(1,Wi(r)2Ci)]TJ /F7 7.97 Tf 6.58 0 Td[(1andW(r)2Ci)]TJ /F7 7.97 Tf 6.59 0 Td[(1Rules 6 and 7 arethemostimportantrules.Rule 6 says,alltheuncommittedreadactions(r2Ai)]TJ /F3 11.955 Tf 12.59 0 Td[(Ci)onlyseethewritesthathappens-beforethem.Rule 7 says,the 5Therearetwootherrules,8and9in[ 60 ],butareomittedin[ 7 ]forbrievity. 30

PAGE 31

Initially,x==y==0Thread1 Thread2 A1:r1=x; B1:r2=y;A2:y=r1; B2:x=r2; Figure2-9. r1==r2==42isanout-of-thin-airresult,andisdisallowedbyJMM. to-be-committedreadactions(r2Ci)]TJ /F3 11.955 Tf 12.5 0 Td[(Ci)]TJ /F7 7.97 Tf 6.58 0 Td[(1)mustseewritesthathavealreadybeencommittedinbothEiandE,butmayseeadifferentwriteinEifromtheoneitseesinE.[ 60 ,Figure8]showsanexampleofjustifyingJMMlegalexecutionbyapplyingcausalityruleslistedabove.Otherthanthesetworules,thehb,so,andVineachjustifyingexecutionmustbethesameastheexecutionbeingjustied.Thecausalityrequirementsareusedtoruleoutout-of-thin-airvalues.Aprecisedenitionofout-of-thin-airvaluesiscomplicated,butwecangettheideathroughlookingatanexample.ConsidertheexampleshowninFig. 2-9 [ 60 ,x2.2],nomatterwhatoptimizationsareapplied,thereisnowaytobringthevalue42intotheexecutions,sor1==r2==42isanout-of-thin-airresultandshouldbeforbidden.Butinafutureaggressivesystem,Thread1couldspeculativelywrite42toy[ 60 ],andthenpropagates42tox.However,thisexecutioniswell-formedaccordingtoDenition 3 .Therearenoviolationsofanyoftheconsistencies.Let'sapplythecausalityrulestoseethisresultisillegalunderJMM.SupposethatwewanttocommitthewriteactionA2:y=r1;.ThenV(A2)isthevaluereadinactionr1=x.Thevalueofxmustbeobtainedfromawritethateitherhappened-beforeA1(theinitializationactionistheonlyoption)orisalreadycommitted.Intheformercase,thevaluereadis0,inthelattercase,itisthevaluewrittenbyB2.Similarly,thevaluewritteninB2mustbethevaluereadinB1,whichmustbeeithercommittedorhappen-beforeit.However,A2wasnotcommitted,sotheinitializationactionistheonlyoption.Thustheonlypossibleoutcomeisr1==r2==0.Sometimes,out-of-thin-airvaluesarenotastrivialasFig. 2-9 .ConsidertheexampleshowninFig. 2-10 [ 41 ].Theresultr1==r2==1,r3==0isawell-formed 31

PAGE 32

Initially,x==y==z==0Thread1 Thread2 Thread3 Thread4 r1=x; r2=y; z=1; r3=z;y=r1; x=r2; x=r3; Figure2-10. r1==r2==1,r3==0isanout-of-thin-airresult,andisdisallowedbyJMM. Initially,x==y==0Thread1 Thread2 r1=x; r3=y;r2=x; x=r3;if(r1==r2) y=1; Figure2-11. UnderJMM,r1==r2==r3==1isallowed. result,butitisout-of-thin-airandshouldalsobeforbidden.Inthisexample,theonlywaytobringvalue1tor1andr2isthroughthereadofzinThread4.Soinordertogetr1==r2==1,r3mustbe1.Byapplyingthecausalityrules,thereisnowaytocommitr1=x(read1)withoutcommittingr3=z(read1)rst. 2.2.3EvaluationofJavamemorymodelTheJavamemorymodelhasamuchmorerelaxedsemanticsthanSCmemorymodel.Itallowsmorehardwareorcompileroptimizationsandtransformations,andmorebehaviorsareallowed.Basedonwell-formedexecutiondenition(Denition 3 ),anon-volatilereadmayseeanyvalueprovidedthatthesourcewritetothatvalueishappens-beforeconsistentwiththeread(Rule 9 ).Areadmayseeeitheravaluewrittenbyawritethathappenedbeforeit(wecallitpreviouswrite)oravaluethattobewrittenafterit(wecallitfuturewrite).FortheexecutionsequenceshowninFig. 1-1 ,thereadofxmayseeeither1or2(previouswrite),or3(futurewrite),andalltheoutcomesareJMMlegal.Notethatvalue3cannotbeseenbythereadunderPSO.AlsotheredundantreadeliminationisallowedinFig. 2-2 andFig. 2-3 .Moreinterestingly,r1==1&&r2==2isallowedintheprogramshowninFig. 2-1 .The 32

PAGE 33

Initially,x==y==0Thread1 Thread2 r1=x; r2=y;y=r1; if(r2==1)f r3=y; x=r3; g elsefx=1;g Figure2-12. Sometimes,theredundantreadeliminationisforbiddenbyJMM. resultcanbeprovedbyDenition 3 andDenition 4 ;thereadsmaysee1and2aftercommittingthewrites.NotethatthisisrestrictedbybothSCmemorymodelandstorebuffer-basedmemorymodels.EvenanotherexampleisshowninFig. 2-11 [ 8 41 ],r1==r2==r3==1isallowedbyJMM,butprohibitedbySCmemorymodel.Wemayusethecausalityrulestojustifyitbyrstcommittingthewritey=1inC1,thencommittingthewritex=r3inC2,andnallycommittingthetworeadsr1=xandr2=xatthesametime.Thecompletejusticationsequencecanbefoundat[ 41 ].Ontheotherhand,JMMstillforbidsmanyhardwareandcompileroptimizationsandtransformationsthoughitisawell-knownrelaxedmemorymodel.SevckandAspinallidentiedsomeoftheseoptimizations/transformations[ 92 ].AninterestingcaseisshowninFig. 2-12 [ 92 ].InanyJMM-legalexecutions,wecannotgetr2==1;wecannotincluder3=yinthejustifyingexecutionsequence.Howeverifthecompilerappliesaredundantreadeliminationbyreplacingr3=ywithr3=r2,thenwecangettheresult.AlthoughJMMforbidscertainoptimizationsandtransformations,itiscurrentlyamostwidelyrecognizedmemorymodelforJava.ThespecicationisalreadyincludedinJavaLanguageSpecication[ 36 ,x17.4].JMMalsoservesasabeaconintheformalizationandconstructionofhighlevelprogramminglanguagememorymodels.Mostnotably[ 12 ]learnedfromJMMwhendesigningthenewC++memorymodel,theC++0x. 33

PAGE 34

2.3DataRaceandProgramCorrectnessConcurrentprogramsarecomplicated,andsometimedifculttodebug.Tohelpprogrammerstowritebetterconcurrentprograms,varioustechniquesareproposed.Insoftwareengineering,vericationmeansusingmethodstocheckwhetheraprogramsatisessomerequirements.Ifaprogramsatisesitsspecication,itisconsideredasacorrectprogram.Toverifythecorrectnessofsequentialprograms,wemayusetheHoareLogic[ 39 ],inwhichtheprogramspecicationisabstractedintermsofpreconditions(P),postconditions(Q),andinvariants(I).SupposeSisastatement,thenwehavethenotationoffPgSfQg.ProgrammermayformallyverifytheprogrambyapplyingtheaxiomsandinferencerulesprovidedbyHoarelogic.Howeverforconcurrentprograms,itisdifculttoapplyhoarelogictoverifytheprogram.Thebestknownattemptis[ 76 ],whereanon-interferencerule6wasproposed.Buttheruleisbasedonastrictinterleavingmodel,inwhichalltheactionsfromdifferentprocessesareexecutedinanarbitrarysequentialorder.Asidefromthedifcultyinvericationofthecorrectnessofconcurrentprograms,researchinconcurrencyhaslongbeenfocusinginanotheraspectofconcurrentprograms,thedetectionofdatarace.Programthatcontainsdataracesisoftenerroneous. 2.3.1DataraceWhatisdatarace?Adatarace,informallyspeaking,isaconditionwheretwoaccessesfromdifferentthreadsaccessingthesamesharedmemorylocation,withatleastoneofthembeingawrite.Andthereisnoexplicitmechanismtopreventtheaccessesfrombeingsimultaneous[ 83 ].Dataraceisverycommoninmultithreaded 6Thisruleisalsosummarizedin[ 6 ,x2.3] 34

PAGE 35

programs.Inmanycases,programerrorsaregeneratedfromdataraces,sodataraceisusuallyconsideredtobeasymptomofbug.Foralongtime,theconcurrentprogramanalysis,bothdynamicallyandstatically,hasbeenfocusingonthedetectionofdataraces.Savageetal.[ 83 ]introducedatoolcalledErasertodynamicallydetectdataracesinconcurrentprograms.Choietal.[ 18 ]raisedadynamicdataracedetectingapproachformultithreadedobject-orientedprograms.Naiketal.[ 66 ]proposedastaticapproachindetectingdataracesinconcurrentJavaprograms.FlanaganandFreund[ 30 ]presentedastaticdataraceanalysisforJavaprogramsbasedonatypesystem.Pratikakisetal.[ 79 ]proposedatoolcalledLOCKSMITHforreasoningdataracesinCprograms.O'CallahanandChoi[ 72 ]presentedadynamicmethodthatcombineslockset-baseddetectionandhappens-before-baseddetection.Chrisiaensetal.[ 19 ]introducedatoolcalledTRaDethatusestopologicalapproach.ItcandetectdataracesinJavaprograms.Kahlonetal.[ 46 ]proposedacontext-sensitiveanalysistodetectdataraces.Despitetheactiveresearchindataracefordecades,thedataraceitselfisavagueconcept.Thereislackofprecisedenitionofdatarace.Manypapersusedtheirowndenition.Unlikeothermemorymodels,Javamemorymodelhasitsformalandprecisedenitionfordatarace[ 60 ].TheJMMdataraceisbasedontwoconcepts:1)conictingaccessesand2)happens-beforeorder.Theconictingaccessesareaccessestothesamesharedmemorylocationwithatleastoneaccessisawrite. Denition5(DataRace). Twoaccessesxandyformadataraceinanexecutionofaprogramif theyarefromdifferentthreads theyconict theyarenotorderedbyhappens-beforepartialordersBasedonDenition 5 ,theexecutionshowninFig. 2-8 isfreeofdataraces.Forthetwosharedvariables,xanddone,anypairsofconictingaccessesareclearlyordered 35

PAGE 36

Initially,x==y==0Thread1 Thread2 r1=x; r2=y;if(r1!=0) if(r2!=0)y=42; x=42; Figure2-13. Correctlysynchronized(DRF)program,r1==r2==0istheonlypossibleoutcome. byhappens-before(L0hbL2hbL3andL0hbL1hbL4).Butifdoneisnotvolatile,thenthehappens-beforefromL2toL3ismissing,andtheexecutioncontainsdataraces.FromDenition 5 ,weseethatJMM'sdenitionondataraceisbasedonexecution,notprogram.Inaddition,JMMalsoprovidesadenitionfordata-race-freeprogram: Denition6(Data-Race-Free(DRF)Program). [ 2 3 60 ]Aprogramissaidtobecor-rectlysynchronizedordata-race-freeifandonlyifallsequentiallyconsistentexecutionsoftheprogramarefreeofdataraces.ThisdenitiontellsusifwecanenumeratealltheSCexecutionsofaprogram,andanypairsofconictingaccessesareorderedbyhappens-before,thentheprogramisDRFprogram.Fig. 2-6 isDRFifdoneisvolatile.AlsotheprograminFig. 2-13 [ 60 ]isDRF;therearenosynchronizationsintheprogram,butinanySCexecutions,thetwoifstatementsarenotexecuted,sotherearenodataracesintheSCexecutions.Onthecontrary,programinFig. 2-1 isnotDRF.Denition 6 providesaniceguidelinefordataracedetection.JRF[ 48 ]isanattempttousemodelcheckingmethodtodetectdataracesunderJMM.InreallifeJavaprograms,dataracecanbeverysubtle.Aproblemcalledsafepublicationisapracticalcaseofdatarace.Publishinganobjectmeansmakingitavailabletocodeoutsideofitsscope.[ 35 ]WheninstantiatingaJavaobject,ifthereferenceisvisiblebyathreadotherthanthethreadthatcreatingit,andthethreadseesapartiallyconstructedobject,thenthispublicationisanunsafepublication.Thereason 36

PAGE 37

. Racy Programs Correct Programs Benign Figure2-14. Therelationshipbetweenracyprograms,correctprograms,andprogramswithbenigndataraces. forreadingpartiallyconstructedobjectisthelackofhappens-beforeorderingbetweentheobjectcreationandthereadofthereference.Thefamousdouble-checkedlockingidiom[ 9 ]containsdataraceandsuffersunsafepublicationproblem. 2.3.2ProgramcorrectnessandbenigndataraceWhatpropertiesdoesaDRFprogramhave?AspinallandSevck[ 7 ]provedthatanylegalexecutionEofawell-formedexecutionofaDRFprogramissequentiallyconsistent. Theorem2.1(DRFGuarantee). AnylegalexecutionEofawell-formeddataracefreeprogramissequentiallyconsistent.ThistheoremimpliesthatJMMguaranteessequentialconsistencyforprogramsthataredataracefree.Sequentialconsistencycanbeunderstoodbyprogrammerseasily,andsequentiallyinconsistentprogramsareoftenerroneous,suchasthePeterson'salgorithminFig. 2-5 .Althoughdataraceisverylikelytoleadtounintenederrors,dataraceisn'tequaltoprogramincorrectness,anddataracefreedoesn'tnecessarilyimplyprogramcorrectness.UnderJMM,dataracefreeonlyguaranteessequentialconsistency,notcorrectness.Wesayaprogramiscorrectifandonlyiftheresultsmeetitsspecication.Somedataracesareactuallybenign;thepresenceofdataracedoesn'taffectthecorrectnessoftheprogram.Wecallthedataracesthatmayleadtoerrorsareharmful 37

PAGE 38

balanceisshared,andisvolatileThread1 Thread2 r1=balance; r2=balance;if(r1>1000)f if(r2>1000)fr1=r1-1000; r2=r2-1000;balance=r1; balance=r2;g g Figure2-15. SometimesDRFprogramiserroneous. dataraces,whiletheracesthatwon'taffectthecorrectnessarebenigndataraces.Therelationshipofracyprograms,correctprograms,andprogramswithbenigndataracesisshowninFig. 2-14 ,wheretheshadedpartbetweenracyprogramsandcorrectprogramscontainsprogramswithbenigndataraces.Theyarecorrectbutcontaindataraces.Ontheotherhand,someDRFprogramsareincorrect.SeeFig. 2-15 ,supposebalancerepresentsabankaccountbalance,twothreadsaretryingtowithdrawfromthesamebankaccount.Inthiscase,evenifbalanceisvolatile,twothreadsmayreaditatthesametimeandonlyone1000isdeductedfrombalance.Thisprogramiscorrectlysynchronized,butsuffersfromatomicityproblem.Benigndataraceisverycommon.AnexampleofbenigndataraceisFig. 2-9 .TheprogramisnotDRF;inanySCexecutionsthewriteofxandthereadofxarenotorderedbyhappens-before.Butifthespecicationisinanyexecution,wecangetr1==r2==0,thentheprogramiscorrect,becauser1==r2==0istheonlypossibleoutcomeofthisprogram.AlsoseetheexampleshowninFig. 2-16 .ThisisthesourcecodeofJava'sStringclass.Theeldsofvalue,oset,andcountaredeclaredasnal7,sono 7InJava,analeldmayonlybegivenavalueintheinitializerandclasseswithalloftheireldsnalareconsideredimmutable.Finaleldsalsohavespecialsemanticswithrespecttothememorymodel:roughlyspeaking,providedthatthethisreferencedoes 38

PAGE 39

1publicnalclassStringf privatenalcharvalue[];//naleldssetinconstructor 3privatenalintoffset; privatenalintcount; 5privateinthash;//hashisnotnal,defaultvalueis0 ... 7publicinthashCode()f inth=hash; 9intlen=count; if(h==0&&len>0)f 11intoff=offset; charval[]=value; 13for(inti=0;i
PAGE 40

ModelCheckerProgramSpecicationcorrect,violation ?eeeee)-400(@ Figure2-18. ModelCheckingStructure. synchronizationsareneeded.Buthashisnotnal,andifthemultiplethreadsareconcurrentlycallinghashCode()methodasshowninFig. 2-17 ,therewouldbeadataraceinvolvinghash;onethreadiswritinghashinline 16 whileanotherthreadisreadinghashinline 8 .However,thisisabenigndatarace,ashashCode()willalwaysreturnthecorrecthashcodenomatterhowmanythreadsarerunningit.Benigndataraceisextremelydifculttoidentifyandtherearenotmanystudiesaboutbenignraces.Narayanasamyetal.[ 67 ]proposedadynamicapproachtoclassifybenignandharmfuldataraces,butitisinaccurate. 2.4ModelCheckingWhenreasoningaboutthecorrectnessofasinglethreadedprogram,formalmathematicalreasoningtechniquessuchasHoarelogic[ 39 ]arewidelyapplied.Butundermultithreadedcontext,becausetherearesomanynondeterminisms,atechniquecalledmodelcheckingisgenerallyused.Modelchecking,denedby[ 44 ],isanautomatictechniqueforverifyingnitestateconcurrentsystems.Formally,modelcheckingisdenedasfollows: Denition7(ModelChecking[ 22 ]). LetMbeaKripkestructure(i.e.,state-transitiongraph).Letfbeaformulaoftemporallogic(i.e.,thespecication).FindallstatessofMsuchthatM,sj=f.Informallyspeaking,werelyonmodelcheckingtoolstocheckwhetherthepropertiesinthegivenspecitionaresatisedbyautomaticallygeneratingallthepossibleexecutingpaths.ThestructureisshowninFig. 2-18 ,wheretheprogramandthespecicationaregivenasaninput,andtheafterexplorationofallthepossiblestates 40

PAGE 41

x=0,y=0er2=xr1=yeey=1r1=yr2=xx=2eeeer1=y,x=2y=1x=2y=1x=2r2=x,y=1eeeeeex=2y=1x=2y=1eeee HHHHHHHHJJJJHHHHHHHH %%%%JJJJeeee r1=1,r2=0r1=0,r2=0r1=0,r2=0r1=0,r2=0r1=0,r2=0r1=0,r2=2Figure2-19. ModelcheckingprograminFig. 2-1 underSCmemorymodel. themodelcheckeranswerswhethertheprogrammeetsitsspecicationornot.Thedifferencebetweenmodelcheckingandsoftwaretestingisthattestingonlyexecuteoneparticularpath,whilemodelcheckingexploresallthepaths.Modelcheckinghasbeenusedinbothconcurrenthardwareandsoftwaresystems.Thekeyprocedureofmodelcheckingisstateexploration.Fig. 2-19 showstheexplicit-stateexplorationstructureofFig. 2-1 underSCmemorymodel.Eachcirclerepresentsastate.Themodelcheckerstartsfromthewriteofthedefaultvaluesandexploresallthepossibleinterleavingofinstructionsfromdifferentthreadsinadepth-rstsearch(DFS)manner.Whenanewstateischosentoexplore,themodelcheckeradvancestothatnewstate.Iftherearenomoreinterleavingchoices,themodelcheckerbacktrackstotheparentstateandmakingotherchoices.Theroutefromtherststatetooneoftheendstatesformsapath.ItatlastexploresallthepathsandgetsallthepossibleoutcomesunderSCmemorymodel.Aftermodelchecking,wendthatr1=1^r2=2isnotvalidunderSCmemorymodel.Wecanseethatevenforthesimpletwo-threaded-two-lineprogram,modelcheckergeneratessomanystates,thenforcomplexprogramsmodelcheckermaygenerate 41

PAGE 42

astronomicalnumberofstates.Thisiscalledstatespaceexplosionproblem.Stateexplorationproblemisamajorlimitationofmodelchecking.Becauseofthestateexplosionproblem,themodelcheckermayrunoutofmemoryeventually.Totacklethisproblem,manymechanmismsaredesignedtoreducethenumberofstates,suchaspartialorderreduction[ 90 ],abstractions[ 23 25 56 ],symbolicmodelchecking[ 61 ],andsymmetricreduction[ 87 ].Othermechanismstoalleviatestateexplosionproblemcanbefoundat[ 63 ]. 2.4.1ModelcheckingtoolsTherearenumbersofmodelcheckingtoolsavaiable.SPIN[ 73 ]isamodelcheckertoverifypropertiesspeciedbyLinearTemporalLogic(LTL)[ 78 ];TVLA[ 54 ]checksreachabilitypropertiesbasedonshapeanalysis,abstraction,and3-valuedlogic;ActionLanguageVerier(ALV)[ 93 ]iscapableofcheckingpropertiesgiveninComputationTreeLogic(CTL)[ 21 ];SLAM[ 10 ]isanon-goingMicrosoftprojectthatisaimedatmodelcheckingsafetypropertiesinCprogramsusingpredicateabstraction;BLAST[ 38 ]isaCmodelcheckerthatusessoftwareabstraction;F-Soft[ 40 ]isanotherCprogrammodelcheckerthatappliesabstractions.OthermodelcheckersincludeNuSMV[ 71 ],MRMC[ 65 ],LTSA[ 57 ],Banderatoolset[ 37 ],JavaPathnder(JPF)[ 42 ],etc.Thesemodelcheckersareeitherexplicitstate,wheretheprogramstatesareexplicitlyexplored;orsymbolic,wherestatesaresummarizedintoformulasorbinarydecisiondiagrams(BDDs)[ 4 ]. 2.4.2JavaPathnderJavaPathnder(JPF)[ 42 91 ]isasoftwaremodelcheckingtoolforconcurrentJavaprogramsdevelopedbyNASA.JPFisexplicit-state,Javabytecodebased.Itcanbeviewedasavirtualmachine(VM)forJava.JPFtakesJavaclasslesasinputandexploresallthepossibleexecutionpathsoftheprogram.Thevericationresultisreturnedafterverication. 42

PAGE 43

Whencheckingprogramcorrectness,JPFcanautomaticallydetectnonfunctionalpropertieslikedeadlocksoruncaughtexceptionscausedbyJava'sassertstatements8.Otherfunctionalpropertiescanbecustomlydened.ThecheckingofthesepropertiesaredonewithJPFlisteners;atcertainpointofanexecution,JPFawakesaneventhandlerwhichcheckssomeproperties.JPFprovidesamechanismcalledChoiceGeneratortohandletheuncertaintieswhenmakingachoice.Threadinterleavingisautomaticallyhandledbythebuilt-inChoiceGenerator.Fordatauncertainties,e.g.whichvaluetochoosewhenreadingavariable,JPFalsoprovidesBooleanChoiceGenerator,IntChoiceGenerator,Double-ChoiceGenerator,etc.tohandlethedatauncertaintiesofsomedatatype.OtherchoicescanalsobespeciedbyextendingChoiceGeneratorclass.JPFishighlyextensible.Itcanbeeasilyextendedformanypurposes.Forexample,JavaRacender(JRF)[ 48 49 ],nowjpf-racender,isanextensionofJPFtopreciselydetectandeliminatedataracesunderJMMdenition;ZhangandBreugel[ 94 ]associatesprobabilitiesintoJPFtomodelchecktherandomizedalgorithms;Nguyenetal.[ 69 ]extendsJPFtocheckifaJavaprogramiscorrectwithregardtoUMLsequencediagramspecication;jpf-ltl[ 68 ]enablesJPFtoverifyLTLpropertiesforsequentialandconcurrentJavaprograms;KebrtandSery[ 47 ]makesJPFtorunJUnittestcases;Leungwattanakitetal.[ 53 ]enablesJPFtomodelchecknetworkedapplications(distributedsystem);jpf-awt[ 62 ]isarecentextensionthatenablesJPFtomodelcheckAWT(AbstractWindowToolkit)programs.JPFimplicitlyassumessequentialconsistencyastheunderlyingmemorymodelwhichmeansonlyexecutionsasshowninFig. 1-1 canbegeneratedbyJPF,i.e.readonlyseesthevalueofthemostrecentwrite,otherpreviouswritesorfuturewritesare 8Anassertstatementcontainsabooleanexpression.Itserveslikeapredicateinsidetheprogram:anerrorwillbereportediftheexpressionisevaluatedtofalse. 43

PAGE 44

invisible.UnderJMM,JPFisonlysoundforprogramswithoutdatarace,becauseonlyDRFprogramsaresequentiallyconsistent.Forthoseprogramswithdataraces,JPFcannotgeneratepossiblesequentiallyinconsistentexecutions.WewilltalkmoreaboutJPF'sdetailsintheJPRimplementationsection(Chapter5). 44

PAGE 45

CHAPTER3THEALGORITHMThischapterpresentsthemainalgorithmofJPR.ThealgorithmisaimedatmodelcheckingconcurrentprogramsunderJMM.Theinputisatargetprogramwithassertstatementstodescribethespecication,andtheoutputistrueorfalse(i.e.whethertheprogrammeetsitsspecicationornot).Thebasicideabehindthealgorithmistomaintainamap,WriteSet,thatmapsmemorylocationstosetsof(writeaction,valuewritten)pairs.Forareadactionofvariablex,insteadofthestandardJPFbehaviorwherethereadseesthevalueofthemostrecentwritetoxonthecurrentpath(whichalsocorrespondstosequentiallyconsistentbehavior),avaluefromanelementofWriteSet(x)ischosen.Thealgorithmisinxed-pointstyle;ItloopsovertoexpandWriteSetandterminateswhenaxed-pointisreached,i.e.WriteSetdoesn'tchange.Throughthisprocess,completelyout-of-thin-airvaluesareavoidedbecauseeachvalueseenbyareadmusthavebeenwritteninsomeexecutionalreadygenerated.ThisalgorithmisdescribedinthecontextofJPF,butcanbeappliedtoanysimilarexplicitstatemodelcheckingtoolswithalistenerstyleinterface.Inthischapter,werstgiveanoverviewofthisalgorithm,thenintroducesomemetadatausedinthealgorithmbeforedescribingthealgorithmindetail.Finallywegiveanexampletoshowhowthealgorithmworks. 3.1AlgorithmOverviewTraditionalmodelcheckingtoolsassumeSCmemorymodelbydefault,sotheyonlyexplorealltheinterleavingofthreads.Fig. 2-19 showstheexplorationstructureofthesemodelcheckers.Eachreadonlyseesthevaluewrittenbythemostrecentwriteaction.Ateachstate,themodelcheckeronlyhastodeterminewhichthreadtochoosefrom,thensimplyselectstherstinstructionthathasn'tbeenexecutedfromthatthread.Therefore,iftheexecutionshowninFig. 1-1 isgeneratedbythesemodelcheckers,the 45

PAGE 46

Initially,WriteSet(x)=f(0,0)g,WriteSet(y)=f(0,0)g 1r2=x(0) 1r2=x(0) 1r2=x(0) 3r1=y(0) 3r1=y(0) 3r1=y(0)2y=1 3r1=y(0) 3r1=y(0) 1r2=x(0) 1r2=x(0) 4x=23r1=y(0,1) 2y=1 4x=2 2y=1 4x=2 1r2=x(0,2)4x=2 4x=2 2y=1 4x=2 2y=1 2y=1 h0,0i,h1,0i h0,0i h0,0i h0,0i h0,0i h0,0i,h0,2i After1strun,WriteSet(x)=f(0,0),(4,2)g,WriteSet(y)=f(0,0),(2,1)gFigure3-1. Theexecutionsof1strunoftheextendedmodelchecker. Initially,WriteSet(x)=f(0,0),(4,2)g,WriteSet(y)=f(0,0),(2,1)g 1r2=x(0,2) 1r2=x(0,2) 1r2=x(0,2) 3r1=y(0,1) 3r1=y(0,1) 3r1=y(0,1)2y=1 3r1=y(0,1) 3r1=y(0,1) 1r2=x(0,2) 1r2=x(0,2) 4x=23r1=y(0,1) 2y=1 4x=2 2y=1 4x=2 1r2=x(0,2)4x=2 4x=2 2y=1 4x=2 2y=1 2y=1 h0,0i,h1,0i h0,0i,h1,0i h0,0i,h1,0i h0,0i,h1,0i h0,0i,h1,0i h0,0i,h1,0ih0,2i,h1,2i h0,2i,h1,2i h0,2i,h1,2i h0,2i,h1,2i h0,2i,h1,2i h0,2i,h1,2i After2ndrun,WriteSet(x)=f(0,0),(4,2)g,WriteSet(y)=f(0,0),(2,1)gFigure3-2. Theexecutionsof2ndrunoftheextendedmodelchecker. underlinedreadcanonlysee2,butnot1(thepreviouswrite),and3(thefuturewrite).Butbothr=2andr=3arelegalresultsunderJMM.Toletreadsseeotherpreviouswrites,oneintuitionistokeepadatastructurethatmaintainsahistoryofallthewriteswithrespecttothememorylocations.Thenatthetimeofread,insteadofreadingthemostrecentwrite,wechoosevaluesfromthehistoryofthecorrespondingmemorylocation.Thisideahasbeenexpressedby[ 26 ],thedatastructureinwhichiscalledWriteSet.WemayviewWriteSetasamappingfrommemorylocationtoapairof(writeaction,valuewritten).WithWriteSet,themodelcheckerneedsnotonlythenondeterminismofthreads,butalsodatanondeterminismwhenperformingaread.Thingsbecomecomplicatedwhenitcomestothefuturewrites.Thisisnotthatstraightforwardtomodel.Becauseatthetimeoftheread,wedon'tknowwhatwillhappeninthefuture,sowecannotkeepahistory.Ourideaistorunthemodelcheckeriterativelysothatthereadmayseethevaluesthatwillbegeneratedinthefuture.Inthe 46

PAGE 47

L0:Initially,0x==y==0Thread1 Thread2 L1:r1=x; L3:r2=y;L2:y=r1+1; L4:x=r2; Figure3-3. Ifreadfromfuturewrite,thatwritemustwritethesamevalueasthevalueread. rstrun,thereadmayonlyseepreviouswrites.Aftertherun,wegetaWriteSetfromthegeneratedexecutions.TheWriteSetisthenpassedtothesecondrun.Inthisrun,thereadstillchoosesvaluefromtheWriteSet,butmayseemorevalues,andhencetheWriteSetmightalsobeexpanded.Let'stakealookattheprograminFig. 2-1 .Initially,theWriteSetonlycontainsthewriteofdefaultvalues(i.e.(x,0),(y,0)).Intherstrun,wegettheoutcomesofFig. 3-1 .Thereadseethevalueofpreviouswrites.NotetheresultsarethesameaswhatweseeinFig. 2-19 .TheWriteSetisexpandedattheendoftheexploration.Inthesecondrunofthemodelchecker,wegettheresultsinFig. 3-2 .Nowthereadsareabletoseethefuturewrites.andtheresultr1=1^r2=2canbegenerated.However,wecannotletreadsseeanywritesnondiscriminately.SeetheexampleshowninFig. 3-3 ,intherstrun,wegetWriteSet(x)=f(L0,0),(L4,1)gandWriteSet(y)=f(L0,0),(L2,1)g.IfareadmayseeanywritesintheWriteSet,thenweshallgetWriteSet(x)=f(L0,0),(L4,1),(L4,2)gandWriteSet(y)=f(L0,0),(L2,1),(L2,2)g.ButaccordingtoJMM'scausalityrules,ifwecommitL2,thenymustwrite1,so2isnotalegalvalue.Basedonthisobservation,ifareadseesafuturewrite,thenthatwritemustactuallywritethesamevalueasthereadsees.Wecallthiswritebeingimposedbytheread.ThenifweapplythisruleinFig. 3-3 ,wewillnotgeneratevalue2.Thisavoidsthosecompletelyout-of-thin-airvalues.InordertocapturethefuturewritesinWriteSet,wecallmodelcheckerinaniterativeway,butitcannotloopforever.Thereisaterminationconditioninthealgorithm.NoteinFig. 3-2 ,theWriteSetafterthe2ndrunisthesameas1strun.IftheWriteSet 47

PAGE 48

-WriteSet0MProgram ? -WriteSet1MProgram ? -WriteSet2rrr -WriteSetn)]TJ /F6 7.97 Tf 6.59 0 Td[(1MProgram ? -WriteSetnFigure3-4. AlgorithmStructure.Aftersomen,WriteSetn)]TJ /F6 7.97 Tf 6.59 0 Td[(1=WriteSetn afterarunisthesameastheWriteSetinthepreviousrun,thentheiterationterminates.Ifweviewthemodelcheckerasafunctionf,andWriteSetasanargumenttof,thenthelastrunbeforeterminationcanbeviewedasf(WriteSet)=WriteSet.Thisconditionisaxedpoint.Inlatticetheory,xedpointisdenedas: Denition8(FixedPoint). [ 70 ,x4.2]Givenamonotonefunctionf:L!LonacompletelatticeL=(L,v,t,u,?,>),axedpointoffisanelementl2Lsuchthatf(l)=landwewriteFix(f)=fljf(l)=lgInChapter4,wewillformallyprovethatouralgorithmcanbeviewedasamonotonefunctionandwecangettoaleastxedpoint(LFP),whichistheterminationconditionfornite-stateprograms.Thexed-pointstylestructureofthealgorithmisshowninFig. 3-4 ,whereMisthemodelchecker,Programistheprogrambeingveried.Initially,wepasstheWriteSet0=?totherstrunofmodelchecking,andgetapossiblyexpandedWriteSet1whichispassedtothenextrun.Aftersomerunn,wegetWriteSetnwhichisthesameasWriteSetn)]TJ /F6 7.97 Tf 6.59 0 Td[(1,andterminatetheiteration.Duringthisprocedure,foranyruni,wehaveWriteSetiWriteSeti+1.WewillexplainthisinmoredetailinChapter4.Besidespreviouswritesandfuturewrites,wemustalsotakecareoftherulesofwell-formedexecution(Denition 3 ),especiallythehappens-beforeconsistencyrequirements(Rule 9 ).Inouralgorithm,wekeepadatastructureHBSettorecordthehappens-beforerelations(hb)inanexecution.Differentexecutionshavedifferenthappens-beforerelations,soHBSetisnotpassedbetweenruns.HBSetcanbeviewedasasetthatcontains(action1,action2)pairs.Thesetisexpandedduringthe 48

PAGE 49

explorationprocedure.Itcontainsalltheprogramorders(po)andsynchronizes-withorders(sw).Therstruleofhappens-beforeconsistencyisthenointerleavingwrite(i.e.69w:W(r)hbwhbr).Thisruleistojustifylegalpreviouswrites;Whenthemodelcheckerisperformingareadonvariablex,itnondeterministicallyselectsapairfromasetof(action,valuewritten)fromWriteSet(x).Ifthewriteactionoftheselectedpairisapreviouswrite,thenitcheckstheHBSet.Thevalueischosenonlyifthewritesatisesthiscondition(i.e.nointerleavingwrite),otherwisethisvalueisdiscarded,andthemodelcheckerselectsanothervalue.Thesecondrule,r6hbW(r),istojustifylegalfuturewrites.Themodelcheckerdoesn'tcheckthisrulewhenperformingread.Allthewritesthatarenotexecutedatthetimeofreadareconsideredtobepotentialcandidatesoffuturewrite.Whenawriteisbeingexecuted,themodelcheckerloopsoverthereadactionsthathadpreviouslyreadfromthewriteandchecksthisrulebyreferringtoHBSet.Ifthisruleisviolatedbysomereads,thecurrententirepathisdiscarded,andthemodelcheckerisbacktrackedtotheparentstate.Basically,ouralgorithmallowsreadactionstoseeanypreviouswritesbyintroducingWriteSet.Itletsreadsseefuturewritesbyrunningmodelcheckeriterativelywhileitalsohasrestrictionstoruleoutcompletelyout-of-thin-airvaluesandexecutionsthatviolatesJMM'swell-formedexecutionrules.Thealgorithmcanbesummarizedas: Readfromanypreviouswrites:UsesWriteSettorecordthewritehistory.ReadchoosesvaluefromWriteSet. Readfromanyfuturewrites:RunmodelcheckeriterativelytocollectfuturewritesintoWriteSet. Ruleoutout-of-thin-airvalues:Rulesoutsomecompletelyout-of-thin-airvaluesbyimposingfuturewrites. Ensurewell-formedexecutions:UsesHBSettorecordhappens-beforerelations.Well-formedexecutionrulesarecheckedwhenperformingreadorwrite. 49

PAGE 50

Thenextsectionintroducesthemetadatathatwillbeusedinthealgorithm. 3.2MetadataOuralgorithmusesWriteSettokeepahistoryofwriteactions.Thisdatastructureispassedbetweendifferentrunsofmodelchecker.BesidesWriteSet,wealsokeepseveralotherinformationthatareexecutionspecic,suchastheHBSet.Theseinformation(metadata)isextendedintothemodelchecker'sstaterepresentation.Inthefollowingmetadatalist,AidisthedomainofactionIDs.AnactionIDisanarbitraryuniqueidentierfortheaction.WewilltalkaboutdifferentactionIDschemesinChapter5.Valisthedomainofvalues.Herevalueisageneralconcept,itcouldbeeitherint,long,oat,double,char,reference,orwhateverkindofdatatype.Locisthedomainofmemorylocations.Intheprogrammemorylocationsarerepresentedbyvariables.Actionisrepresentedbyatupleofht,k,v,ui.ItisformallydenedinDenition 1 Path:Sequenceofactionidsthatrepresentthecurrentpathofexecution.Foragivenactionidaid,Path(aid)representstheindexofthatactionid,wherePath(aid)is1fortheidoftherstexecutedactioninPath. WriteSet:Loc!2AidValmapsamemorylocationtoasetofactionID,valuepairs,whereeachactionisaWRITE. ActionSet:2Actioncontainstheactionsthathavebeenexecutedonthecurrentpathsofar. HBSet:2AidAidisasetofpairsofactionIDswherehaid1,aid2i2HBSet*ifandonlyifbothareinActionSetandaid1hbaid2andwhereHBSet*isthetransitiveclosureoftherelationrepresentedbyHBSet. ImposeSet:2AidValisasetofactionID,valuepairs,whereeachactionisaWRITE.Inawell-formedpath,ifareadactionrobtainsavaluevalfromwriteactionwwhichmaybeexecutedinthefuture,wmustoccuratsomepointinanywell-formedpathcontainingr,anditmustactuallywriteval.ThustheImposeSetmapswriteactionstovaluesimposedonthembypastreads. Read:Aid!AidbooleanValmapsREADandVOLATILEREADactionIDstoatriplecontainingthewriteactionitsees,i.e.W(rid)andthevalueitreturns, 50

PAGE 51

W(V(rid))foractionidrid.ThebooleanvalueindicateswhethertheW(rid)occuredinthefutureonthecurrentpath. Write:Aid!ValmapsWRITEandVOLATILEWRITE.actionIDstothevaluewrittenbythecorrespondingaction,i.e.V(wid). ThreadLast:Tid!Aidmapsathreadidtothelatestactionperformedbythethreadandisusedtomaintaintheprogramorder,po.NotethatthereisalsoaWriteSetinthemetadata,butthisisnottobeconfusedwiththeWriteSetthatispassedbetweenruns.Thisoneisalocalcopytoastate.TodistinguishbetweenthetwoWriteSets,wecalltheWriteSetwhichispassedbetweenrunstheGlobalWriteSet.Whenarunofmodelcheckingbegins,theGlobalWriteSetofthelastruniscopiedtotheWriteSetoftherststate.Asthemodelcheckermakesadvancements,theWriteSetofthecurrentstateiscopiedtothenewstates,andnewpairsareappendedintotheWriteSetaccordingtothememoryoperationsinvolvedintheadvancement.Attheendstateofeachpath(i.e.thestatehasnochoicetomake,andthemodelcheckerwillbacktracktotheparentstate),wetakeaunionoftheWriteSetofthisstatewiththeGlobalWriteSet.HeretheActionSetrecordstheactionsexecutedsofar.Itisexpandedwhenanewmemoryoperationisexecuted.Wemaydeterminewhetherawriteactionwispreviouswriteorfuturewritebycheckingifw2ActionSetistrueornot.TheHBSetisthesetthatrecordsthehappens-beforerelationsbetweentheactionsthathavebeenexecutedsofar.TheImposeSetkeepsahistoryoftheimposedwriteactions.Aswementionedinthelastsection,thisisusedtoruleoutsomecompletelyout-of-thin-airresults.TheWritecanbeviewedasthevalue-writtenfunction(V).TheReadrecordsthevalueareadsees,thesourcewriteaction,andwhetheritisapreviouswriteorafuturewrite.TheThreadLastisusedtoconstructtheprogramorderwithineachthread.Thesemetadataiscarriedalongwithstate.Eachstatehasaseparatecopyofthemetadata.TheyarenotpassedbetweenrunsliketheGlobalWriteSet.Wecanformallydescribeastateas: 51

PAGE 52

=hPath,WriteSet,ActionSet,HBSet,ImposeSet,Read,Write,ThreadLasti. 3.3FormalDescriptionThissectionformallydescribesthealgorithm.Thealgorithmispresentedinapseudocode,andislistenerstyled.Beforedescribingthealgorithmindetail,wewillrstlyintroducelistenerstyleandJPF'sstatestackstructure.ListenerStyle,alsocalledObserverPattern,orPublish-SubscribePattern[ 32 ,x5],isoneofthebehavioralsoftwaredesignpatterns.Underlistenerstyle,thesystemhasoneobject(calledpublisher)andoneormoredependents(calledsubscriberorlistener)registeredtothepublisher.Whenthereisanevent(thestateofthepublisherischanged),thesubscribersarenotiedandtakeactionsaccordingly.Whileontheotherhand,thesubscribersmayalsochangethestateofthepublisher.Thisisaone-to-manydependencyrelationship.ListenerstyleiswidelyusedinJava,whereSwingisagoodexample.Listeneristypicallyaninterfacewitheacheventaseparatemethod.Programmersimplementtheinterfacetoletitperformaccordingtotheevents.ThelistenersinJavaareallsubinterfacesofEventListener.JPFisalsoinlistenerstyle.TheeaseofextensionofJPFislargelyduetotheusageoflistenerstyle.BeforerunningJPF,oneormorelistenersareregisteredtoit.UponreceivingofeventsfromJPF,thelistenersmayrespondaccordingly.TheeventsofJPFvaryfromsearcheventsandVMevents.Thesearcheventsincludeallthestatespacesearchevents,suchasstateadvanced,statebacktracked,staterestored,searchnished,etc.TheVMeventsincludeJPFvirtualmachine-basedevents,suchasinstructionexecuted,threadstarted,threadblocked,objectcreated,choicegeneratoradvanced,etc.ThemainfunctionofouralgorithmiswritteninJPFlistenerstyle.IttakesactionsaccordingtotheJPFevents;modifythemetadata,expandtheGlobalWriteSet,andmayalsoaffectthesearchprocessofJPF(addingmorechoicestoastateandforcebacktracking). 52

PAGE 53

. 1 2 3 choice#=1 choice#=3 choice#=0 Stateadvance Statebacktrack push pop Figure3-5. ThestackstructureofJPFstateexploration.Theshadedblocksrepresentschoicesthathavealreadybeenselected;theemptyblocksrepresentsthecurrentavailablechoices. ThestateexplorationofJPFisinastackstructure(seeFig. 3-5 ).Anumberofchoicesareattachedtoeachstate.Thechoicecanbeeitheraschedulingchoice(i.e.whichthreadtochooseinthenextstep),ordatachoice(i.e.whichdatatochoosefrominthenextstep).Atastate,JPFtraversesitsunselectedchoices,makesaselection,andadvancestoanewstateaccordingly(i.e.anewstateispushedontothetopofthestack).Ifthestatehasnomoreunselectedchoices,JPFperformsastatebacktrackaction(i.e.popthestateonthetopofthestack).InFig. 3-5 ,therearenomoreavailblechoicesforthestateontopofthestack,soJPFpops3.Nowthetopstatebecomes2whichhasthreeunselectedchoices.JPFthenchoosesonechoicefromthem,markitasselected,performsaccordingly,andthenpushesanewstateontothestack.Ifastatedoesn'thaveanychoiceswhenitispushedonthestack,wesaythatJPFisreachingtheendofapath.JPFstopswhentherearenomorestatesonthestack.Basically,thealgorithmofJPRiscomprisedoftwocomponents: JMMAwareJPFDriverofJPR.ItcallsJPFiterativelyandpassesGlobalWriteSet. JMMListenerThelistenerstyledalgorithmthatisregisteredtoJPF. 53

PAGE 54

JMMAwareJPF(Program) 2GlobalWriteSetold GlobalWriteSetnew ; converged false 4while:convergeddo CallJPF(JMMListener(GlobalWriteSetold)) 6GlobalWriteSetnew JMMListener.GlobalWriteSetnew ifGlobalWriteSetnew==GlobalWriteSetoldthen 8converged true else//notconverged 10GlobalWriteSetold GlobalWriteSetnew endwhile Figure3-6. JMMAwareJPF,thetoplevelalgorithminJPR. TheJMMAwareJPFalgorithmgiveninFig. 3-6 servesasJPRdriver.Theinputofthealgorithmistheprogrambeingveried.Initially,theGlobalWriteSetisempty,andtheconvergeconditionissettofalse.TheGlobalWriteSetoldistheGlobalWriteSetofthelastiteration,andGlobalWriteSetnewistheGlobalWriteSetofthecurrentiteration.Afterinitialization,thealgorithmcallsJPFiteratively.Ineachiteration,theJPRspeciclistener,JMMListener,isregisteredtoJPFwithGlobalWriteSetoldpassingtoit.AfterexecutionofJPF,theJMMListenerreturnsGlobalWriteSetnew,whichisanewandnon-decreasingGlobalWriteSetcollectedfromthecurrentiteration.WecomparetheGlobalWriteSetnewwithGlobalWriteSetold.Iftheyareequal,thentheiterationterminates.JMMListenerisdescribedinFig. 3-7 andcontinuedinFig. 3-8 .ItisthelistenerthatisregisteredtoJPF.AsvariouseventsinJPF(i.e.startsearch,advancestate,backtrack,executeaninstruction,asrepresentedbythevariablesearchEventinFig. 3-7 )occur,acorrespondingcodesegmentisexecuted.TheJPFsearcheventsarelistedinFig. 3-7 ,andtheVMeventINSTRUCTIONEXECUTESislistedinFig. 3-8 .1 1OtherVMevents,includingthreaddivergenceevents(i.e.threadstart,threadjoin,etc.)andobjectcreationeventintroducespecialsynchronizes-withorders,andtheywillbediscussedinmoredetailinChapter5. 54

PAGE 55

1JMMListener(GlobalWriteSetold) GlobalWriteSetnew ;//NewglobalWriteSet 3:hPath,WriteSet,ActionSet,HBSet,ImposeSet,Read,Write,ThreadLasti //Currentstatemetadata 5switch(searchEvent) caseSEARCHSTARTS: 7WriteSet GlobalWriteSetold ActionSet HBSet ImposeSet ; 98loc:Read(loc) undef,Write(loc) undef 8tid:ThreadLast(tid) undef 11Stack.push() caseSTATEADVANCES: 13Stack.push() caseSTATEBACKTRACKS: 15 Stack.pop() ifENDOFPATHthen 17ifpathiswell-formedthen GlobalWriteSetnew GlobalWriteSetnew[WriteSet 19elseignorewritesetanddiscardpath caseINSTRUCTIONEXECUTES: 21SeeFig. 3-8 Figure3-7. JMMListeneralgorithm JMMListenertakesGlobalWriteSetold,theGlobalWriteSetofthelastiterationofJPF,asaninput,andcalculatesGlobalWriteSetnew,theGlobalWriteSetofthecurrentiterationofJPF.Initially,theGlobalWriteSetnewisempty.isarepresentationofthecurrentstateofJPF.Itisatuplethatcontainsallthemetadataintroducedinx 3.2 .Whensearchstarts,wecopyGlobalWriteSetoldtotheWriteSetof,andinitializeallothermetadatatoemptysetsorundenedmappings.Thenwepushtheinitializedontothetopofthestatestack(Fig. 3-5 ).ispushedontothestackwhenJPFadvancestoanewstate.WhenJPFbacktracks,thestateonthetopofstackispoppedandcopiedtothecurrentstate.Attheendofasearchpath,thepathistestedtoseeifitiswell-formed,i.e.allthewritesthatthereadshaveseenwereactuallyexecutedinthisiteration.Ifso,theWriteSetofthelaststateonthepathisunionedwiththeGlobalWriteSetnew,otherwise 55

PAGE 56

theWriteSetofthecurrentstate,aswellastheentirepatharediscarded.2ThenJPFperformsstatebacktrackoperation,andsearchforotherpaths.NowweexplainFig. 3-8 indetail.WhenamemoryrelatedactionisexecutedbyJPF,anactiontupleaction=(aid,tid,kind,loc)isformed.TheaidiscalculatedbyoneoftheactionIDschemesintroducedinChapter5.TheactionisthenappendedtoActionSet.TheprogramorderisformedbyappendingahbrelationfromtheIDofthelastactioninthecurrentthread(ThreadLast(tid))toaid(Line 24 ),andtheThreadLast(tid)isupdated.TheisRELEASEandisACQUIREfunctionsdeterminewhethertheactionisarelease(i.e.unlock,volatilewrite)oracquire(i.e.lock,volatileread).Forreleaseactions,ifitisavolatilewrite,weupdatetheWritefunctionof.Foracquireactions,weloopoverthereleaseactionsonthesamelocinActionSetandaddthehappens-beforerelationstoHBSet.Iftheacquireactionisavolatileread,weassignthevalueofthemostup-to-datevolatilewriteofloctoRead(aid).ThisisaccordingtothedenitionofvolatilekeywordinJava.Iftheactionisawritetoanon-volatilevariable,thenwehavetodeterminewhetheritisafuturewritebylookingintoImposeSet.ImposeSetrecordsthewritesthatfuturelyread(i.e.beingreadbeforeactualexecution)bysomereadactions.Ifitisnotafuturewrite,thenupdateWrite(aid)withthevalueitiswritten,andanewpairisappendedtoWriteSet(loc).Ifitisafuturewrite,thenwehavetochecktwothings:1)whetherthevaluewrittenbythewriteisthesameasthevaluebeingreadbypreviouslybyaread;and2)whetheritsatisesthe1struleofhappens-beforeconsistency(i.e.r6hbW(r))(seeDenition 3 ).1)isstraightforwardbecauseImposeSetrecordsthevalueinformation.For2),weloopoverallthereadsrtolocfromActionSet,andcheck 2Althoughnotshowninthealgorithm,becausepathsmaybediscarded,assertionviolationsarenotreporteduntiltheendofthepathisreached.ThisisadeparturefromstandardJPFbehavior,whichreportsassertionviolationswhentheyoccur. 56

PAGE 57

22caseEXECUTINGACTIONwhereaction=(aid,tid,kind,loc): ActionSet ActionSet[factiong//addcurrentactiontoactionset 24HBSet HBSet[f(ThreadLast(tid),aid)g//updatehbduetopo ThreadLast(tid) aid 26ifisRELEASE(kind)then ifkind==VOLATILEWRITEwritingvalthen 28Write(aid) val elseifisACQUIRE(kind)then 30//foreachreleaseactionrelthatsyncswithactiondo foreachrel=(raid,rtid,rkind,rloc)s.t.isRELEASE(rel)^(raid,aid)2HBSetdo 32HBSet HBSet[f(raid,aid)g//updatehbduetoso ifkind==VOLATILEREADthen 34//letlatestdenotethemostrecentvolatilewritethatsyncswithaction letlatest=(lid,ltid,lkind,lloc)s.t.lkind==VOLATILEWRITE^ 36(lid,aid)2HBSet^69((ak,aid)2HBSet^Path(ak)>Path(lid)) //SavethewriteactionandvalueinRead.Thisisalwaysapastwrite. 38Read(aid) (lid,false,Write(lid)) elseifkind==WRITEofvaluevalthen 40//ifthiswriteactionisintheimposeset,checkforwell-formedness ifforsomeval0,(aid,val0)2ImposeSetthen 42ifval06=valthen backtrack//valuewrittenisnottheimposedvalue,abandonthepath 44else//checkforhbconsistency if9r2ActionSet:Read(r.aid)==(aid,true,)^r.aidhbaidthen 46backtrack//nothbconsistent,abandonpath //elsepathisstillwell-formed,savevaluesandcontinue 48Write(aid) val WriteSet(loc) WriteSet(loc)[f(aid,val)g 50elseifkind==READthen non)]TJ /F25 10.909 Tf 8.49 0 Td[(deterministicallychoose(w,val)2WriteSet(loc)do 52ifw2ActionSetjaidthen//thisisapastread //checkforhbconsistency 54if(69wa:wa2ActionSet^wa.kind==WRITE^wa.loc==loc ^whbwa.aid^wa.aidhbaid)//hbconsistentpastread 56thenRead(aid) (w,false,Write(w)) else//hbinconsistentpastread 58continuewithnextwritesetentry else//potentialcandidateforafutureread 60if69((w,val0)2ImposeSet^val06=val)then ImposeSet ImposeSet[f(w,val)g 62Read(aid) (w,true,val)//trueindicatesfuturewrite else//illegalfutureread,wasinimposesetwithinconsistentvalue 64continuewithnextwritesetentry Figure3-8. JMMListeneralgorithmcontinuedfromFig. 3-7 57

PAGE 58

thehappens-beforerelationfromHBSetbetweenrandthethecurrentwrite.Iftheactionviolateseither1)or2),thenJPFisforcedtodoastatebacktrackoperation(Line 42 and 46 ),otherwiseupdateWrite(aid)withthevalueitiswritten,andanewpairisappendedtoWriteSet(loc)likepreviouswrites.Iftheactionisareadofanon-volatilevariable,thenwechoosea(w,val)pairfromWriteSet(loc)non-deterministically(Line 51 ).Herenon-deterministicallyactuallymeansbyaddingdatachoicesforthecurrentstate.ThenwedeterminewhetherwisapreviouswriteorafuturewritebycheckingifwisincludedintheActionSet.NotethatonlyactionsthathavealreadybeenexecutedcanbeaddedtoActionSet.Ifwisapreviouswrite,thenwehavetocheckthe2ndruleofhappens-beforeconsistency,i.e.69w0toloc,s.t.W(r)hbw0hbrbyreferringtoHBSet(Line 55 ).Iftherearenointerleavingwritestoloc,thenupdatetheRead(loc),otherwiseignorethis(w,val)andselectthenextpairfromWriteSet(loc).Ifwhasn'tbeenexecutedsofar,thenwewillcheckImposeSettoseeifwisimposedbyotherreadsthatexecutedpreviously.Ifnootherreadshaveimposedw,orwisimposedbyotherreadsbutthevaluetheyimposedisthesameasval,thenweregardwasapotentialcandidateoffuturewriteandupdateRead(aid)accordingly,otherwisethisisanillegalfutureread,andselectthenextpairfromWriteSet(loc).Herethepotentialfuturewritemightbeinvalidatedatthetimeofthatwriteifthevaluewrittenisdifferentfromvaloritviolateshappens-beforeconsistency.Inthisalgorithm,therearethreeplaceswhereentirepathwouldbeabandonedbecauseoftheillegalfuturewrite.Therstplaceisline 19 ofFig. 3-7 ,wheretheendofapathisreached.ThealgorithmloopsoverImposeSettoseewhetheralltheimposedwriteactionsareactuallyexecutedonthispath.Thepathwillbediscardediftheconditionfails.Thesecondplaceisline 42 ofFig. 3-8 .Whenanon-volatilewriteisimposed,thenwecheckwhethertheimposedvalueisactuallythevaluebeingwrittenbythewrite.Thethirdplaceisjustacoupleoflinesbelow(line 46 ofFig. 3-8 ).Ifthe 58

PAGE 59

. s)]TJ /F7 7.97 Tf 6.59 0 Td[(1 t0x=0,y=0 s0 s1 s13 a1r2=x b1r1=y s2 s8 s14 s19 a2y=1 b1r1=y a1r2=x b2x=2 s3 s9 s11 s15 s17 s20 b1r1=y a2y=1 b2x=2 a2y=1 b2x=2 a1r2=x s4 s6 s10 s12 s16 s18 s21 s23 0 1 b2x=2 a2y=1 b2x=2 a2y=1 0 2 s5 s7 s22 s24 b2x=2 b2x=2 a2y=1 a2y=1 [r1=0,r2=0] [r1=1,r2=0] [r1=0,r2=0] [r1=0,r2=0] [r1=0,r2=0] [r1=0,r2=0] [r1=0,r2=0] [r1=0,r2=2] Figure3-9. 1stiterationofJPRontheprogramshowninFig. 2-1 .Herethedashedarrowsrepresentdatachoicesandsolidarrowsrepresentthreadchoices. non-volatileisimposedanditviolateshappens-beforeconsistency,thenweforceJPFtobacktrack.Inalltheseplaces,apotentialfuturewritemaycauseviolationofthewell-formednessofapath.Sowhenareadisreadingfromawritethathasn'tbeenexecuted,thealgorithmpotentiallyallowsit,andmaydiscarditlateron.Anassertionviolationonapathmaynotreecttheincorrectnessbecausethepathwouldlaterbediscarded.Becauseofthisfeatureoffuturewrite,thereportofassertionerrorshouldbedelayed.InJPF,assoonasanassertionisviolated,itthrowsanexceptionandterminates.ButinJPR,theassertionerrorshouldbereportedattheendofthepath.WewilltalkmoreonthisinChapter5. 3.4AnExampleInthissection,wepresentasimpleexampletoillustratehowthealgorithmworks. 59

PAGE 60

State ActionSet WriteSet(x) WriteSet(y) HBSet Read s)]TJ /F7 7.97 Tf 6.59 0 Td[(1 ; ; ; ; x:undef s0 t0 (t0,0) (t0,0) ; x:undef s1 t0,a1 (t0,0) (t0,0) (t0,a1) a1:(t0,0) s2 t0,a1,a2 (t0,0) (t0,0),(a2,1) (t0,a1),(a1,a2) a1:(t0,0) s3 t0,a1,a2,b1 (t0,0) (t0,0),(a2,1) (t0,a1),(a1,a2),(t0,b1) a1:(t0,0) s4 t0,a1,a2,b1 (t0,0) (t0,0),(a2,1) (t0,a1),(a1,a2),(t0,b1) a1:(t0,0),b1:(t0,0) s5 t0,a1,a2,b1,b2 (t0,0),(b2,2) (t0,0),(a2,1) (t0,a1),(a1,a2),(t0,b1,(b1,b2)) a1:(t0,0),b1:(t0,0) s6 t0,a1,a2,b1 (t0,0) (t0,0),(a2,1) (t0,a1),(a1,a2),(t0,b1) a1:(t0,0),b1:(a2,1) s7 t0,a1,a2,b1,b2 (t0,0),(b2,2) (t0,0),(a2,1) (t0,a1),(a1,a2),(t0,b1,(b1,b2)) a1:(t0,0),b1:(a2,1) s8 t0,a1,b1 (t0,0) (t0,0) (t0,a1),(t0,b1) a1:(t0,0),b1:(t0,0) s9 t0,a1,b1,a2 (t0,0) (t0,0),(a2,1) (t0,a1),(t0,b1),(a1,a2) a1:(t0,0),b1:(t0,0) s10 t0,a1,b1,a2,b2 (t0,0),(b2,2) (t0,0),(a2,1) (t0,a1),(t0,b1),(a1,a2),(b1,b2) a1:(t0,0),b1:(t0,0) s11 t0,a1,b1,b2 (t0,0),(b2,2) (t0,0) (t0,a1),(t0,b1),(b1,b2) a1:(t0,0),b1:(t0,0) s12 t0,a1,b1,b2,a2 (t0,0),(b2,2) (t0,0),(a2,1) (t0,a1),(t0,b1),(b1,b2),(a1,a2) a1:(t0,0),b1:(t0,0) s13 t0,b1 (t0,0) (t0,0) (t0,b1) b1:(t0,0) s14 t0,b1,a1 (t0,0) (t0,0) (t0,b1),(t0,a1) b1:(t0,0),a1:(t0,0) s15 t0,b1,a1,a2 (t0,0) (t0,0),(a2,1) (t0,b1),(t0,a1),(a1,a2) b1:(t0,0),a1:(t0,0) s16 t0,b1,a1,a2,b2 (t0,0),(b2,2) (t0,0),(a2,1) (t0,b1),(t0,a1),(a1,a2),(b1,b2) b1:(t0,0),a1:(t0,0) s17 t0,b1,a1,b2 (t0,0),(b2,2) (t0,0) (t0,b1),(t0,a1),(b1,b2) b1:(t0,0),a1:(t0,0) s18 t0,b1,a1,b2,a2 (t0,0),(b2,2) (t0,0),(a2,1) (t0,b1),(t0,a1),(b1,b2),(a1,a2) b1:(t0,0),a1:(t0,0) s19 t0,b1,b2 (t0,0),(b2,2) (t0,0) (t0,b1),(b1,b2) b1:(t0,0) s20 t0,b1,b2,a1 (t0,0),(b2,2) (t0,0) (t0,b1),(b1,b2),(t0,a1) b1:(t0,0) s21 t0,b1,b2,a1 (t0,0),(b2,2) (t0,0) (t0,b1),(b1,b2),(t0,a1) b1:(t0,0),a1:(t0,0) s22 t0,b1,b2,a1,a2 (t0,0),(b2,2) (t0,0),(a2,1) (t0,b1),(b1,b2),(t0,a1),(a1,a2) b1:(t0,0),a1:(t0,0) s23 t0,b1,b2,a1 (t0,0),(b2,2) (t0,0) (t0,b1),(b1,b2),(t0,a1) b1:(t0,0),a1:(b2,2) s24 t0,b1,b2,a1,a2 (t0,0),(b2,2) (t0,0),(a2,1) (t0,b1),(b1,b2),(t0,a1),(a1,a2) b1:(t0,0),a1:(b2,2) Figure3-10. Themetadataofthestatesinthe1stiteration.ThestatenumberiscorrespondingtoFig. 3-9 Let'sapplythealgorithmtotheprogramshowninFig. 2-1 .Supposewelabelthedefaultwriteast0,theactionsofThread1asa0anda1,andtheactionsofThread2asb0andb1,thenthestateexplorationofthe1stiterationofthealgorithmisFig. 3-9 .Thevaluesofr1andr2arelistedattheendofeachpath.Thestateisnumberedaccordingtothedepth-rstsearchorderbyJPF.TheexplorationissimilartoFig. 2-19 ,exceptthedashedtransitions.Thedashedtransitionsaregeneratedduetodatachoices;Areadmayseenotonlythemostrecentwrite,butanypreviouswrites,whiletheSCmemorymodel-basedmodelcheckersonlyhaveschedulingchoices. 60

PAGE 61

Thestates'metadataareshowninFig. 3-10 .PathisnotshowninthetablebutisreectedbytheactionorderofActionSet.TheImposeSetisemptyforallthestatesbecauseinthe1stiteration,readscannotseefuturewrites,soitisnotlisted.AlsoThreadLastandWritearetrivialandareomitted.Tosavespace,thefuturelyreadsignalinReadisignored.TheHBSetcolumncontainsonlythedirecthappens-beforerelation.Whencheckingthehappens-beforeconsistency,wemustcalculatethetransitiveclosureofit.s)]TJ /F7 7.97 Tf 6.59 0 Td[(1istheinitialstateofJPF.InitiallytheWriteSetisempty.Thereareacoupleofplaceswhereareadmayseeapreviouslywritten,butnotup-to-datevalues,namelys4ands21.Ins4,b1isreadingfromt0.Fromthetransitiveclosureofs4'sHBSet,thereisnowritewtoysuchthatt0hbwhbb1,sothisisalegalread.Theunderlinedstatesarethelaststatesonapath.Beforebacktrackingfromthesestates,theWriteSetisunionedwithGlobalWriteSetnew.Afterthe1stiteration,weget:GlobalWriteSetnew(x)=f(t0,0),(b2,2)gandGlobalWriteSetnew(y)=f(t0,0),(a2,1)g.ThisGlobalWriteSetnewisthenpassedtothe2nditeration.WiththeexpandedGlobalWriteSet,thesearchspaceofthe2nditerationisgreatlyexpanded.Forsimplicity,weonlyshowaparticularpathinFig. 3-11 .Therearealotmoredatachoices(dashedarrows)inthe2nditeration.Thisenablesustogetr1==1&&r2==2viapathw)]TJ /F7 7.97 Tf 6.59 0 Td[(1!w0!w20!w21!w22!w25!w26.Thestates'metadataofpathw)]TJ /F7 7.97 Tf 6.59 0 Td[(1!w0!w20!w21!w22!w25!w26isshowninFig. 3-12 .Otherstates'metadataisnotlistedforbrevity.Initially,theGlobalWriteSetofthelastiterationispassedtotheWriteSetofw)]TJ /F7 7.97 Tf 6.59 0 Td[(1.WhenJPFisexecutinga1,therearetwodatachoicesfromWriteSet;0(previouslywrittenbyt0)and2(futurewritebyb2).Ifwechoose2asthevalueseenbytheread,thenweshouldimposeb2towrite2byadding(b2,2)totheImposeSet.Thenatstatew26whenb2isexecuted,wemustdeterminewhethertheimposedvalueisactuallywritten.Inthiscase,b2writes2whichjustiestheImposeSet.Furthermore,wemustalsocheckthehappens-beforeconsistencybyreferringtothetransitiveclosureofHBSet.Inthiscase,a1isreading 61

PAGE 62

. w)]TJ /F7 7.97 Tf 6.58 0 Td[(1 t0x=0,y=0 w0 w1 w38 a1r2=x b1r1=y w2 w20 0 2 w21 w27 a2y=1 b1r1=y w22 b1r1=y w23 w25 0 1 w26 b2x=2 [r1=1,r2=2] Figure3-11. 2nditerationofJPRontheprogramshowninFig. 2-1 .Herethedashedarrowsrepresentdatachoicesandsolidarrowsrepresentthreadchoices. State ActionSet WriteSet(x) WriteSet(y) HBSet ImposeSet Read w)]TJ /F7 7.97 Tf 6.58 0 Td[(1 ; (t0,0),(b2,2) (t0,0),(a2,1) ; x:undef x:undef w0 t0 (t0,0),(b2,2) (t0,0),(a2,1) ; x:undef x:undef w1 t0,a1 (t0,0),(b2,2) (t0,0),(a2,1) (t0,a1) x:undef x:undef w20 t0,a1 (t0,0),(b2,2) (t0,0),(a2,1) (t0,a1) (b2,2) a1:(b2,2) w21 t0,a1,a2 (t0,0),(b2,2) (t0,0),(a2,1) (t0,a1),(a1,a2) (b2,2) a1:(b2,2) w22 t0,a1,a2,b1 (t0,0),(b2,2) (t0,0),(a2,1) (t0,a1),(a1,a2),(t0,b1) (b2,2) a1:(b2,2) w25 t0,a1,a2,b1 (t0,0),(b2,2) (t0,0),(a2,1) (t0,a1),(a1,a2),(t0,b1) (b2,2) a1:(b2,2),b1:(a2,1) w26 t0,a1,a2,b1,b2 (t0,0),(b2,2) (t0,0),(a2,1) (t0,a1),(a1,a2),(t0,b1),(b1,b2) (b2,2) a1:(b2,2),b1:(a2,1) Figure3-12. Themetadataofthestatesinthe2nditeration.ThestatenumberiscorrespondingtoFig. 3-11 62

PAGE 63

fromb2,and69a1hbb2,soitsatisesthehappens-beforeconsistency.Fromthispath,wegetr1==1&&r2==2.Thesameasthe1stiteration,attheendofeachpath,theWriteSetisunionedwithGlobalWriteSet.Afterthe2nditerationofJPF,theGlobalWriteSetisthesameasthe1nd,sotheiterationterminates. 63

PAGE 64

CHAPTER4ALGORITHMPROPERTIESInthischapter,wediscussthepropertiesofJPRanditsbasicalgorithms(Figs. 3-6 3-7 ,and 3-8 ).ThemainresultsarethatJPRonlygeneratespathscorrespondingtowell-formedexecutionsandthatthesetofpathsgeneratedisanoverapproximationoftheJMM.ExecutionsaretheabstractionusedintheJMManddenedinDenition 2 whilepathsarethetotallyorderedsequencesofactionsgeneratedbyJPR.WesaythatpathpcorrespondstoexecutionE=hA,P,po,so,W,ViwhereAisthesetofactionsthatoccurinp,Pisprog,poistheunionoverallthreadsofpathrestrictedtoeachthread,andsoispathrestrictedtothesynchronizationactionsinp.Ifanon-volatilereadrusesWriteSetentry(w,val),thenW(r)=wandV(w)=val.V(w)iswell-denedsinceallreadsofthesamewriteactioninapathmustgetthesamevalue.Foraxedprogram,prog,usuallyconsideredtobeunderstood,andlettingWSbethetypeofWriteSet,letJPRprog:WS!WSPathsbeafunctionthattakesaws2WSandreturnsanewWSandasetofpathspaths.JPRprogisafunctionrepresentsaninvocationofJPFseeninFig. 3-6 ,wherePathsisthesetofpathssearchedbyJPF.Forws2WSandpathp,wesaythatwsJPR!pifp2JPRprog(ws).paths.WesaythatwsJPR!pif9i0:p2(JPRiprog(ws)).paths1.Forconvenience,weoverloadJPR!andJPR!andalsosaywsJPR!ws0orwsJPR!ws0withtheobviousmeanings. 4.1Safety,Completeness,andConvergence Lemma1(HBSet). JPRaccuratelyrecordshbforanygeneratedpathporprexofapath.Itisinvariantthatfor8ai,aj2p:ai6=aj:aihbaj(ai,aj)2HBSet_(9ak:(ai,ak)2HBSet^(ak,aj)2HBSet). 1Ifi=0,pmustbeempty. 64

PAGE 65

Proof. Theproofisstraightforwardbyinductiononthelengthofapath.Newelementsofhbcanbecreatedduetoprogramorderonathread,orwhenanacquireoperationisperformed.Theformerishandledinline 24 inFig. 3-8 whilethelatterishandledinline 32 Proposition4.1(Safety). Letwsscbethesetof(w,v)pairsseeninthesequentiallyconsistentexecutionsofprog.IfwsscJPR!p,thenpcorrespondstoawell-formedexecutionofprog. Proof. SincepathsaregeneratedfromasoundmodelcheckerexecutingaproperlycompiledJavaprogram,mostoftherulesforawell-formedexecutionholdbyconstruction.Rule 9 holdsbecauseofLemma 1 andthetestin(Fig. 3-8 ,line 55 ). Proposition4.2(Completeness). JPRprog(ws)generatesapathcorrespondingtoeverywell-formedexecutionofprogsatisfying(8readsr2A:(W(r),V(W(r)))2ws). Proof. Thispropositiondependsonthebehavioroftheunderlyingmodelchecker,namelythatitwillexploreallofitschoices.Supposethereissuchawell-formedpathpthatisnotgeneratedbyJPRprog(ws)andletp0bethelongestprexofpthathasbeensearched.Therearetwopossibilities.Oneisthatthelastactioninp0causedittobediscarded.Thiswillhappeninfourcircumstancesinlines 42 46 57 ,and 63 ofFig. 3-8 .However,alloftheseindicateatviolationofwell-formedness.Theotherpossibilityisthattherstactionainp)]TJ /F3 11.955 Tf 12.39 0 Td[(p0isnevertaken.IfaisaREAD,thenthiswouldmeanthatthemodelcheckerfailedtotakeanavailablechoiceatline 51 .Ifaisnotaread,thenthemodelchecker'ssearchstrategyfailedtoexploreavalidtransition.Eithercaseviolatesourbasicassumptionaboutthecompletenessofthemodelchecker2. Lemma2(MonotonicityofJPRprog). JPRprogismonotonic,i.e. 2BecausewehavenotstudiedtheinteractionofJPF'spartialorderreductionwiththelistenerdescribedinFigs. 3-7 and 3-8 ,weuseJPFwithoutthisfeature. 65

PAGE 66

wsws0andJPRprog(ws)=(ws1,paths)andJPRprog(ws0)=(ws01,paths0)thenws1ws01,andpathspaths0. wsws1. Proof. FollowsfromthefactthatelementsareneverremovedfromtheWriteSet. Theorem4.1(Convergence). Fornitestate,terminatingprogramprog,SupposethatJPRprogisappliediterativelystartingwithws0.TheprocesswillreachaxedpointwsinanitenumberofstepsandtheresultingwswillbetheleastxedpointofJPRprogatleastws0. Proof. Notingthatthe(nite)setof(ws,paths)pairswithsubsetinclusionformacompletelattice,theresultfromtheKnaster-Tarskixedpointtheorem[ 88 ]andLemma 2 .InKnaster-Tarski'stheorem,ifLisacompletelattice,andiff:L!Lisamonotonefunction,thenthesetofxedpointsoffisalsoacompletelattice.Thisimpliesthattheleastxedpointoffisthebottomofthecompletelatticesoitcanbeachievedbyperformingnitenumberofsteps. 4.2OverapproximationInthissection,weformallydescribethemostimportantpropertyofJPR,theoverapproximationofJMM.Werstlypresentthetheoremandproofs,thengivetwoexamplestoshowtheoverapproximation.Finally,westatetherelationshipoftheexecutionsgeneratedbyJPRwithlegalexecutionsofothermemorymodels. Lemma3(Pathswithonlypastreadsaregenerated). Letwsscbeaninitialwritesetformedbycollectingvalueswritteninthesequentiallyconsistentexecutionsofprog.Thenforeachpathpcorrespondingtowell-formedexecutionEthatdoesnotreadfuturevalueswsscJPR!p. Proof. Theproofisbycontradiction.Supposethereisapathpcorrespondingtowell-formedexecutionEthatdoesnotreadfuturevaluesanditisnotthecasethatwsscJPR!p.Letprebethemaximalprexofpsuchthatpreisaprexofsomep0where 66

PAGE 67

forsomewritesetwsp0,wsscJPR!wsp0JPR!p0.Notethatpreincludesatleasttheinitializationactionsandisthusnotempty.Now,considerthenextactionaafterpreinp.WearguethatwsscJPR!wsp0JPR!pre@a.Thisactionisnotinp0.Byassumption,ifaisanyoperationotherthanaread,itwillbegeneratedbyJPRprog(wssc),thusamustbeareadsuchthatW(a)isnotananyWriteSetgeneratedbywsp0.ButsinceaisapastreadW(a)isinpre,andthusinCVprog(wsp0).WS. Lemma4(PathswithreadsinpastorinWriteSetaregenerated). Letwsibeawritesetwherewsscwsi.Thenforeachpathpcorrespondingtowell-formedexecutionEwhereeachrreadsapastwriteorawriteinwsi,wsiJPR!p. Proof. FollowsfromProp 4.2 andLemma. TheJMMdenesalegalexecutionasonethatcanbeobtainedviaasequenceofso-calledcommittingexecutionswheretheexecutionsinthesequencearerelatedtoeachotherbyasetofconstraints.AccordingtoTheorem 4.2 ,ifwegenerateallthepathscorrespondingtosomecommittingexecution,thenwewillalsogenerateallthepathsinanyexecutionthatcouldpossiblycomenextinthecommittingsequence. Theorem4.2(Overapproximation). LetwsscbethesmallestWriteSetcontainingallofthevaluesseeninthesetofsequentiallyconsistentexecutionsofnitestate,terminatingprogramprogandwsscbetheleastxedpointofJPRprogatleastwssc.LetJPRprog(wssc).pathsbethesetofpathsgeneratedbywssc.LetJmmLegalprogbethesetoflegalpaths.ThenJmmLegalprogJPRprog(wssc).paths. Proof. AnexecutionEofprogislegalifthereisasequenceofjustifyingexecutionsE0,E1,...,EnsatisfyingtherequirementsforlegalexecutionsinDenition 4 .Sinceweareonlyconsideringnitestate,terminatingprograms,En=E.WewillprovebyinductionthatapathcorrespondingtoeveryEifor1iinavalidjustifyingsequenceisgeneratedbyJPRprog(wssc).ConsiderexecutionEiwithacommitsetCi.Withoutlossofgenerality,weassumeaminimalEwhereAibetheminimalsetofactionssuch 67

PAGE 68

Initially,x=y=z=0Thread1 Thread2 Thread3 Thread4 A1:r1=x B1:r2=y C1:z=1 D1:r3=zA2:y=r1 B2:x=r2 D2:x=r3 Figure4-1. AlabeledversionofFig. 2-10 .JPRproggeneratesapathwithr1==r2==1&&r3==0.ThisisnotlegalaccordingtoJMM'scausalityrules. thatCiAiandEiiswell-formed.LetwsibetheWriteSetthatgeneratesapathcorrespondingtoEi.Basecase:Thereisapathp1correspondingtoE1suchthatwsscJPR!p1.BecauseC0=,Denition 4 ,rule 6 requiresthatforallreadsrinA1,W(r)hbrandarethusinthepast.Theresultfollowsfromlemma 4.2 .Inductionstep:AssumethatapathcorrespondingtoEiwithcommitsetCihasbeengeneratedbyJPRprog(wsi).NowconsiderexecutionEi+1withcommitsetCi+1.Fromproposition 4.2 ,itsufcesthatallwritesw2Ai+1areinwsi+1wherewsiJPR!wsi+1.FromDenition 4 ,rule 4 ,forallwriteactionswinCi+1,thesamevaluearewritteninEi,Ei+1,andE,i.e.Vi(w)=Vi+1(w)=V(w).Fromrule 5 ,forallthereadactionsrinCi,thesamewritesareseeninEi,Ei+1,andE,i.e.Wi(r)=Wi+1(r)=W(r).Further,foreachr2Ci,W(r)2wsi.ThusweareonlyconcernedwiththewritesinAi+1)]TJ /F3 11.955 Tf 12.38 0 Td[(Ci.Fromrule 7 ,foranyreadr2Ci+1)]TJ /F3 11.955 Tf 10.38 0 Td[(Ci,Wi+1(r)2Ci,andthusinwsi.Fromrule 6 ,foranyreadr2Ai+1)]TJ /F3 11.955 Tf 12.29 0 Td[(Ci+1,Wi+1(r)hbi+1r.ThusallallreadsinAi+1areeitherinwsiorarepastreads.Fromlemma 4 ,forsomepathpi+1correspondingtoEi+1,wsiJPR!pi+1. TheaboveresultsshowthatthesetofpathsgeneratedbyJPRprogisanoverapproximationoftheJMM.Asapracticalmatter,thismeansthatJPRissound:ifweshowthatadataraceisbenignbytesingwithJPRthenwecanconcludethataprecisetool(ifoneexisted)wouldalsonditbenign.Ontheotherhand,theoverapproximationallowsfalsealarms.Below,wediscussthesourceoftheimprecisioninJPR. 68

PAGE 69

. A1:r1=x; A2:y=r1; B1:r2=y; B2:x=2; C1:z=1; D1:r3=z; D2:x=r3; Figure4-2. ValuepropagationofFig. 4-1 IntheexampleshowninFig. 4-1 ,JPRgeneratesapathwithresultr1==r2==1&&r3==0.ThereisavalidpathwhereactionD2writes1,A1readsD2,A2writes1,B1readsA2,B2writes1.Then,onthenextiteration,A1readsfromB2(andimposes1onB2),B1readsfromA2,andthenB2successfullywrites1asimposedbyA1,whileD1readsfromthedefaultwriteaction(value0).However,thisisnotlegalaccordingtoJMM.Inorderforr1==r2==1toappearinaJMM-legalexecution,D2wouldneedtobeacommittedactionwithV(D2)==1.Butthenr3mustalreadybe1,sotheexecutionisnotlegal.Thevalue1isconsideredtocomeout-of-thin-airinanyexecutionwherer3==0.Fig. 4-2 showshowthevalue1ispropagatedtothefragmentinthedashedbox.Intherstiteration,ispassedalongC1!D1!D2!A1!A2!B1!B2.Intheseconditeration,canbepassedfromB2toA1,thenA1!A2!B1!B2!A1formsaloopondatadependencies.NotethatthisprogramisthesameprogramasFig. 2-9 withtheadditionoftwootherthreads,Thread3and4whichintroduceanout-of-thin-airvaluetotheexecution.InFig. 2-9 ,JPRdoesnotgeneratepathswithout-of-thin-airvalues.YetanotherexampletoshowJPRgeneratesanoverapproximationofJMMisFig. 4-3 .JPRcouldgenerater1==1&&r2==1&&r3==2.Intherstiteration,toletz=1execute,thestatementsintheelseshouldbeexecuted.Thenintheseconditeration,r1seesthefuturewriteofzof1.z=1isimposedandthenThread1enterstheif.Thread2thengetr2==1andr3==2,andwrites1toz.Thiswritejusties 69

PAGE 70

Initially,x=y=z=0Thread1 Thread2 r1=z; r2=x;if(r1==1)f r3=y;x=1; if(r2+r3==3)y=2; z=1;g Figure4-3. r1==1&&r2==1&&r3==2isillegalresultbyJMM,butgeneratedbyJPR. r1=z; if(r1==1)f x=1;y=2; gelsefx=2;y=1;g r2=x;r3=y; if(r2+r3==3) z=1; Figure4-4. DataandcontroldependenciesofFig. 4-3 .Herethesolidarrowsshowthedependenciesinthe1stiteration;thedashedarrowsshowadependencyloopformedinthe2nditeration. theimposedvalueandwegetr1==1&&r2==1&&r3==2.ButthisresultisprohibitedbyJMM.Applyingthecausalityrules,inE0,allthereadsonlyseethewritesthathappens-beforethem.Soonlytheelseisexecuted.Theninordertocommitz=1wemustrstcommittheactionsinelse.Sothereisnowaytocommittheactionsinif.Fig. 4-4 showsthedataandcontroldependenciesofFig. 4-3 .Intherstiteration,actionsintheelsemakez=1tohappen.Intheseconditeration,r1seesthefuturewriteofzsotheifbranchexecutes.InterestinglybothifandelselettheconditioninThread2betrue.Soadependencyloopisformed(thedashedarrows)fromif.Thisloopcausestheillegalresultr1==1&&r2==1&&r3==2togenerate.Suchloopiscalledcausalcyclein[ 60 ],buttheconceptisnotformallydened.Earlyexecutionofanactiondoesnotresultinacausalcycleifitsoccurrenceisnotdependentonaread 70

PAGE 71

. SCMM executions JMMexecutions JPRgeneratedexecutions Happens-beforeMMexecutions Figure4-5. RelationshipbetweentheexecutionsgeneratedbyJPRandlegalexecutionsofSCmemorymodel,JMM,andHappens-beforememorymodel. returningavaluefromadatarace[ 60 ].Inthisexample,theearlyexecutionofz=1isdependedondataraceswithxandyinvolved.JMM'scausalityrulesareaimedatdetectingsuchcausalcycles,butJPR'salgorithmdoesn'tcheckthisbecausecheckingitisveryexpensive.Fromthetwoexamples,weseethatJPRmaygeneratesomeillegalpathswithout-of-thin-airvaluesonlywhentheout-of-thin-airvaluesactuallydoappearinsomegeneratedpath.Itdoesnotgeneratecompletelyarbitraryout-of-thinairvalues.JPRcouldbemademoreprecisebytrackingimposerequirementsacrossiterationsanddependentactionsatthecostofsignicantlyincreasedtimeandspaceoverhead.TherelationshipbetweentheexecutionsgeneratedbyJPRandlegalexecutionsofSCmemorymodel,JMM,andHappens-beforememorymodelisshowninFig. 4-5 .Happens-beforememorymodelisasimplermemorymodelthanJMM.Basicallyitrequiresanexecutiontosatisfysynchronizationorderconsistencyandhappens-beforeconsistency,butnocausalityrulesisrequired.SCmemorymodelhasthesmallestexecutionspace.JPRgeneratesanoverapproximationofJMM,butalsorulesout 71

PAGE 72

certainkindsofout-of-thin-airresultssotheexecutionspaceissmallerthanthatofhappens-beforememorymodel. 72

PAGE 73

CHAPTER5IMPLEMENTATIONThischapterdescribestheimplementationissuesinvolvedindevelopingJPR.WeidentifyanambiguationinJMMontheactionIDdenition(elementuinDenition 1 ).WithoutaproperdenitiononactionID,itisdifculttorelateactionsbetweendifferentiterations.Inthischapter,werstlystatetheactionIDambiguationproblem,andproposefouractionIDschemes,ofwhichthreeschemesareactuallyimplementedinJPR.Thenwedescribetheoverallstructureofthetool.Finally,welistsomeselectedmajorimplementationissuesandprovidethesolutions.TheimplementationissuesaregroupedintoJPF-relatedissuesandnon-JPFrelatedissues. 5.1JMMDisambiguationOneofthedifcultiesencounteredwhenimplementingJPRwasthelackofawell-denedconnectionbetweenthenotionofexecutionsusedtodenetheJMMandactualJavaprograms.ThismanifesteditselfintherepresentationoftheactionID.InDenition 1 ,JMMonlyspeciesthatanarbitraryuniqueidentieruisassociatedwithanaction,butdoesn'texplainhowtoensuretheuniqueness,neitherdoesitexplainhowtoobtaintheidentier.Withinasingleexecution,thebasicrequirementoftheactionIDsisuniqueness.However,boththeJMMdenitionoflegalexecutions(Denition 4 )andJPRrequirethattheidentityofactionsbecomparedacrossdifferentexecutionsandpaths,i.e.wemustbeabletodetermineif,say,awritetoxinoneexecutionorpathisthesameactionasawritetoxinanotherbycomparingtheirIDs.RecallthatinDenition 4 ,Ci)]TJ /F7 7.97 Tf 6.58 0 Td[(1Ci.ItrequiresthatalltheactionsthathavealreadybeencommittedinEi)]TJ /F7 7.97 Tf 6.58 0 Td[(1mustalsobecommittedinEi.ButJMMdoesn'ttellushowtorelatetheactionsinEi)]TJ /F7 7.97 Tf 6.59 0 Td[(1andEi.Thisbecomesproblematicforprogramswithbranches. 73

PAGE 74

Weconsideredfourapproachestoidentifyactions.Lettbethethreadthattheactionbelongsto,kbetheactionkind1,vbethememorylocation(i.e.variable),andvalbethevaluereadfromorwrittento. Occurrence (k,t,v,n).ncountsoccurrencesofactionsofkindkbythreadtonvariablev.Withthisapproach,thenthread(orwrite)ofaparticularvariableisalwaysconsideredtobethesameaction,regardlessofwhathappensinbetween,andwhetherornottheinstructionsoccurinthesameplaceinthesourcecode. Scope (t,S,n).Sreferstothelexicalscopeoft,repeatedinvocationsofthesameinstruction,suchasinalooparedifferentiatedbyasequencenumbern.Here,actionsaredistinguishedbytheirlocationinthesourcecode,withrepeatedinvocationsofthesameinstruction,suchasinaloop,differentiatedbytheirsequencenumbers. Value (k,t,v,val).Actionswiththesamek,v,andtaredistinguishedbythevalue.Thisistheapproachusedin[ 17 ]butitisnotadequatebecauseactionsarenolongeruniquelyidentiedifathreadwritesthesamevaluetoavariablemorethanonce.Forthisreason,wehavenotpursuedthisapproach. Occurence-Val (k,t,v,val,n).Addsanoccurencecount(n)tovaluewiththeconsequencethatforawritew,V(w)alwaysmapstothesamevalue.Thisisanattempttorescuethevalueapproachbydistinguishingdifferentactionsofthesamekindthatoperateonthesamevariablewiththesamevaluewithacounter.Thistanglesthenotionofanactionsetwiththevalue-writtenfunctionVsothatforawritew,V(w)alwaysmapstothesamevalue,makinglegalityrules 4 and 7 inDenition. 4 redundantandinoperative,respectively. 1Forbrevity,weonlyrestrictattentiontoreadandwrite.Othersynchronizationactionslikelockandunlockdon'tassociatewithvalues,sowemayjustcounttheoccurrencewithregardtothemonitors. 74

PAGE 75

Initially,x==y==0Thread1 Thread2 r1=x; r2=y;y=r1; if(r2<2) x=3; x=2; (a)r1==r2==2isallowedbyapproachscopebutforbiddenbyapproachoccurrence. Initially,x==y==0Thread1 Thread2 r1=x; r2=y;y=r1; if(r2==1) x=1; else x=1; (b)r1==r2==1isallowedbyapproachoccurrencebutforbiddenbyscope.Figure5-1. ActionIDexamplesI.Comparisonbetweenscopeandoccurrence. Thedifferentapproachesyielddifferentsetsoflegalexecutions.ConsiderFigs. 5-1b and 5-1a .ApproachoccurrenceallowstheoutcomeinFigs. 5-1b becausebothassignmentstoxareconsideredtobethesameaction;ifcommitted,theassignmentscouldbeincludedinthejustifyingexecutions.However,itforbidstheoutcomeinFig. 5-1a sincetheassignmentx=2intwodifferentexecutionsmayhavedifferentactionIDsdependingonwhetherornotthebranchwastaken.Ifthebranchistaken,thenitisthesecondwritetox,otherwiseistherstwritetox.ApproachscopeallowstheindicatedoutcomeinFig. 5-1a becauseregardlessoftheexecutionorder,x=2iswithinthesamelexicalscopeandcanbecommittedandveried.ItdoesnotallowtheoutcomeinFig. 5-1b becausethetwox=1actionsarewithindifferentscopesandifoneiscommitted,itisimpossiblefortheactiontobeincludedinsubsequentvericationexecutions.Fig. 5-2 showsthedifferentinterpretationsofJMMbetweenoccurrenceandoccurrence-val.Theresultr1==r2==1isallowedbyoccurrence-val,butforbiddenbyoccurrence.Usingoccurrence-val,wemayrstlycommitx=1inE1.Thisactionistherstwritetoxwithvalue1inThread2.Thenwecancommitr1=x(1),y=r1(1),andr2=y(1)inthesubsequentjustifyingexecutions.Nowthebranchistaken,andwegetx=2andx=r2(1)toexecute.Herex=r2isalsotherstwritetoxwithvalue 75

PAGE 76

Initially,x==y==0Thread1 Thread2 r1=x; r2=y;y=r1; if(r2==1)f x=2; x=r2; gelsef x=1; g Figure5-2. ActionIDexamplesII.r1==r2==1isallowedbyoccurrence-val,butforbiddenbyoccurrence. 1inThread2,thesamevalueiswrittenasx=1inE1,sowecancommitittojustifyCi)]TJ /F7 7.97 Tf 6.58 0 Td[(1Ci.However,usingoccurrence,aftercommittingx=1(therstwritetoxinThread2,itwrites1)inE1,andr1=x(1),y=r1(1),andr2=y(1)inthefollowingjustifyingexecutions,wecannotgofurther,becausenowtherstwritetoxinThread2becomesx=2whichwritesvalue2,not1.ThisviolatesWijCi)]TJ /F17 5.978 Tf 5.75 0 Td[(1=WjCi.Basedupontheobservations,weseethatdifferentdenitionontheactionIDmayleadtocompletedifferentinterpretationsofJMM,butJMMmakesthisissueopenwithoutgivenclarications.InordertocomparetheactionIDschemes,wehaveimplementedscope,occurrence,andoccurrence-valinJPR.AnanalysisofdifferentschemesbasedonexperimentsisincludedinChapter6.Aconclusionontheschemesisdesirable,howeveritisactuallyveryhardtotellwhichoneisbetterthantheother.OurndingisaremindertotheJMMdesignerstogiveamuchclearerdenitiononthis. 5.2JPRStructureTypically,extensionstoJPFarerealizedbylisteners.AstandardJPFextensionusuallyregistersproject-speciclistenerstoJPFandrunsJPFonlyonce.Allthepropertiescanbecollectedthroughthelisteners.Projectssuchasjpf-racender[ 48 ]andjpf-awt[ 62 ]arestandardJPFextensions.JPRisnotastandardextension,becauseitcallsJPFiteratively. 76

PAGE 77

. JPRDriver JPF JMMListener JavaPathRelaxer Iterativecall GlobalWriteSetnew GlobalWriteSetold events Bytecode Figure5-3. TheoverallstructureofJavaPathRelaxer(JPR). Werealizedthealgorithmdescribedinx 3.3 asastandaloneprojectontopofJPF.ThestructureoftheimplementedJPRisshowninFig. 5-3 .Basically,therearethreecomponents:1)JPRdriver,2)JPFcore,and3)JMMListener.JPRdriverrealizesJMMAwareJPFalgorithm(Fig. 3-6 ).ItiterativelycallsJPF,whichisregisteredwithJMMListener.JMMListenerrealizesthealgorithmshowninFig. 3-7 andFig. 3-8 .TheprogrambeingveriedisinJavabytecode(.classle),thecompiledcodeforJavavirtualmachinetoexecute.Thespecicationiswrittenintermsofassertstatements.Initially,GlobalWriteSetoldthatispassedbetweeniterationsisempty.Beforeeachiteration,JPRdriverpassestheGlobalWriteSetoldoftoJMMListenerandregistersJPFwithJMMListener.JPFtakestheJavabytecodeofthetargetprogramanddoesmodelchecking.Ateachevent(schedulingeventorVMevent),JPFnotiesJMMLis-tenerwhichaccordinglytakesoperationsonthemetadata(x 3.2 ).Ontheotherhand,JMMListenermayalsoinuencethestateexplorationprocedureofJPFbyaddingmoredatachoices,orbyforcingJPFtodostatebacktrackoperations.Attheendofeachiteration,JPRdrivergetstheGlobalWriteSetnewfromJMMListenerandcomparesitwithGlobalWriteSetold.Theiterationprocessstopswhenaxedpointisachieved(i.e.GlobalWriteSetnew=GlobalWriteSetold).Iftheassertionsinthetargetprogram 77

PAGE 78

aresatisedduringthisprocess,thentheprogrammustbecorrectunderJMM.Ifanassertionisviolatedatthenendofapath,JPRstopsandreportedanexception.RememberJPRoverapproximatesJMM(x 4.2 ).ItgeneratesmoreexecutionsthanJMM,soitispossiblethataJMM-legalprogramfailsinJPR. 5.3JPF-relatedImplementationIssuesInthissection,wediscusssomeJPF-relatedimplementationissuesandpresentoursolutions. HeapStructure.JPFusesaheapstructuretomaintaintheobjectsandarrays.Eachobjectorarrayoccupiesanelement(calledElementInfo)ontheheap.Theelementisuniquelyidentiedbyanindex.SotheheapcanbeviewedasacollectionofElementInfos.Theeldsandarraymembersarestoredinsidetheelementasacell.AnobjecteldisrepresentedbyFieldInfo.Inx 3.2 ,weusedLoc(thememorylocation)asthekeyforWriteSet,Read,Write,etc..InJPF,thekeyisrepresentedbyElementInfo,andFieldInfoorarrayelementindex: Fieldaccess(obj.):(classname)@(objectindex).(eldname) Arrayaccess(arr[i]):(arraytype)@(arrayindex).(elementnumber) ActionID.Asstatedinx 5.1 ,JMMisambiguousontheactionID.Weexplained4schemesforactionID.WhenimplementingJPR,weimplementedscope,occurrence,andoccurrence-val.valuewasnotrealizedbecauseitsuffersnon-uniqueproblem.Whenencounteringanaction,anactionIDisretrievedfromdifferentimplementationsofgetID()method. 5.3.1Bytecode-actiontranslationJPFisbasedonJavabytecode;Theprogrambeingveriedisspeciedbytecode,butJMMisdenedontopofmemoryrelatedactions.BytecodeisasetofinstructionsdesignedforJavaVirtualMachine(JVM).Itisinverylowlevelandisstack-based;Thebytecodeinstructionsoperatesononeoperandstack.Thefulllistofbytecodecanbefoundat[ 55 ].InJMM,anactionisrepresentedbyht,k,v,ui,wherekcanbe 78

PAGE 79

non-volatileread/write,volatileread/write,lock,unlock,andotherspecialsynchronizationactionssuchasthreadstart,writetothedefaultvalues,etc.ItisdenedinhigherlevelthanJavabytecode.BeforeimplementingJPR,weneedtoformamappingfromJavabytecodetoJMMactions. Table5-1. Javabytecode-JMMactionmapping. JavaBytecodeaJMMAction geteld,getstaticnon-volatilereadorvolatilereadputeld,putstaticnon-volatilewriteorvolatilewriteaaload,iaload,faload,baload,caloadnon-volatilereadaastore,iastore,fastore,bastore,castorenon-volatilewritemonitorenterlockmonitorexitunlocknew,newarraywritetothedefaultvaluesinvokevirtualthreadstart,threadjoin aOnlymemoryrelatedbytecodesarelisted. Table 5-1 summarizesabytecodetoactionmapping.geteldandgetstaticretrievevaluefromastatic2ornon-staticeld,thenpushthevalueontotheoperandstack.ThesetwoinstructionscanbetreatedasJMMreadactions.Whethertheactionisvolatileornon-volatilecanbedeterminedbyreferringtotheelddeclaration.puteldandputstaticsetaeldwiththevalueontopoftheoperandstack.Likegeteldandgetstatic,theycorrespondtoJMMwriteactions.geteld,getstatic,puteldandputstaticaregroupedbyJPFasFieldInstructions.aaload,iaload,faload,baload,andcaloadarearrayreadinginstructions.Theyretrieveanentryvaluefromanarrayandplacethevalueontheoperandstack.Thetypeofthearrayisdistinguishedbytheirrstletter.Forexample,imeansintegerarray,andameansreferencearray.Similarly,aastore,iastore,fastore,bastore,andcastorearearray 2Staticeldsarealsocalledclassvariables.Theyarespecialeldsthatareassociatedwiththeclass,notaspecicobject. 79

PAGE 80

writinginstructions.Theygetavaluefromthetopofthestackandstoreittoanarrayentry.Thearrayload/storeinstructionscanalsobeviewedasJMMread/writeactions.However,noneofthemcanbevolatileactions.Althoughanarraycanbedeclaredasvolatile,itonlyguaranteesreadstothereferenceofthearrayseethemostup-to-datevalue,butthereisnoguaranteefortheindividualentries.InJPF,thearrayinstructionsarecategorizedasArrayLoadInstructionsandArrayStoreInstructions.monitorenterandmonitorexitaremonitorinstructions.monitorentergivestheexecutingthreadtheownershipofanmonitoriftherearenootherthreadsowningthatmonitor.monitorexitreleasesthemonitorfromtheexecutingthread.ThesetwoinstructionsaremappedtoJMM'slockandunlockrespectively.JPFgroupthemasLockInstructions.newandnewarrayallocatememoryspaceforanobjectandanarrayrespectively.Theobjecteldsandarrayentriesareinitializedtothedefaultvalues.TheycanbemappedintoJMM'swritetodefaultvalues.Basedon[ 36 ,x17.4.4],thewriteofdefaultvaluetoeachvariablesynchronizes-withtherstactionineverythread.Thisisnotspeciedinthealgorithmbecauseitisspecial.Wewilltalkmoreonthisinafollowingsubsection.Thethreadstartandthreadjoinarehandledbyvirtualmethodsstart()andjoin()inJava.Inbytecode,invokevirtualdispatchestoavirtualmethod.InJPF,threadstartisalsocapturedbythreadStartedevent. 5.3.2JPFstaterepresentationJPF'sstateisrepresentedbygov.nasa.jpf.jvm.SystemStateclass.Itmainlycapturesthechoices(calledChoiceGenerator)associatedwiththestate.Inx 3.2 ,wementionedthatinJPR,JPF'sstaterepresentationisexpandedwithmetadata=(Path,WriteSet,ActionSet,HBSet,ImposeSet,Read,Write,ThreadLast).Howeverinreality,weuseaseparatestack(calledstatestack)torecordthemetadatainthecurrentimplementationofJPR.ThisstackoperatestogetherwithJPFpathexploration,andismaintainedby 80

PAGE 81

JMMListener.WhenastateAdvancedeventiscapturedbythelistener,thestatestackpushesthecurrentstateontothestack.Similarly,atstateBacktrackedevent,thetopofstatestackisremovedandcopiedto.AnintuitivealternativeapproachwouldhavebeentoextendJPF'sSystemStatewiththemetadata.ThiswouldhavesimpliedthecontrolofJPR;whenanill-formedpathisgenerated,simplyrequestingabacktrackwouldsufce.However,giventhelackofaninterfaceallowingtheextensionofJPFsstaterepresentation,followingthealternativeapproachwouldhaverequiredmodicationofjpf-core.Asanextension,itisnotdesirabletomodifythekernelofJPF. 5.3.3GarbagecollectionGarbagecollection(GC)isamemorymanagementmechanismusedbyprogramminglanguages(Java,C++,C#,Lisp,etc.)torecyclememoryspacesthatarenolongerinuse.AgarbageinJavacanbeviewedasanobjectthatisnotreferenced.GCisanimportantmechanismbecauseitallowsprogrammertoreusememoryspace. SupposetheconstructorofHelperinitializesaeldxHelperhisasharedreferenceThread1 Thread2 h=newHelper(3); h=newHelper(5); intr2=h.x; Figure5-4. JPFGarbageCollection:AfterterminationofThread1,theobjectcreatedbyThread1willnotbeseenbyThread2. JPFalsohasGCfeatures.Typicallywhenathreadterminates,alltheobjectcreatedinthisthreadwillbegarbagecollected.SeetheexecutionsequenceshowninFig. 5-4 .SupposeThread1rstcreatesaninstanceofHelperatmemorylocationL1andassignsittothesharedreferenceh,thenThread1terminates.Thread2createsanotherHelperinstanceatlocationL2andassignsittoh,andaccesseldxofthatreference.AccordingtotheJMM,thereadinThread2couldreturneither3or5(theeldvaluesofHelperinstancescreatedatL1andL2respectively).However,becauseof 81

PAGE 82

theterminationofThread1,theinstancecreatedinL1isconsideredasnotreferencedandisautomaticallygarbagedcollectedbyJPF.Inordertoallowsuchresults,JPFgarbagecollectionfeatureshouldbeturnedoffforsharedreferences.InJPF,wemaytelltheheapmemorytostopgarbagecollectionatsomereferencebycallinggov.nasa.jpf.jvm.Heap.registerPinDown()method. 5.3.4ReadingfutureobjectsUnderJMM,anon-volatilereadmayseeanywrite,eitherinthepastorinthefuture,tothatvariable,aslongashappens-beforeconsistencyismaintained.Thereisnoproblemwhenreadingfromafuturewritetovariablesofprimitivedatatypes(i.e.int,oat,doubleetc);WesimplyretrievethevaluefromWriteSetandputitontheoperandstacktoletJPFcontinue.However,readingareferencefromfuturewritebecomesproblematicbecausetheobjectatthatreferenceisnotyetcreatedatthetimeofread.WhenJPFistryingtoaccessthereference,anullpointerexceptionwillbethrown.Asanexample,seetheexecutionsequenceshowninFig. 5-5 .SupposeintherstiterationofJPR,Thread1createsaHelperinstanceatL1andThread2createsanotherinstanceatL2,sointheend,WriteSet(h)containstwopairs(a1,L1)and(a3,L2).Intheseconditeration,giventhatexecutionsequence,thereadata2mayseeeithertheinstanceatL1(previouswrite)orL2(futurewrite),buttheinstanceatL2hasnotbeencreatedatthattime,soanexceptionwillbethrownfromJPFifreadingfromthatreference. SupposetheconstructorofHelperinitializesaeldxHelperhisasharedreferenceThread1 Thread2 a1h=newHelper(3); a2intr1=h.x; a3h=newHelper(5); Figure5-5. Read`future'object:NullpointerexceptionisthrownwhenThread1readstheobjectthathasnotbeencreatedbyThread2. 82

PAGE 83

Tosolvethisproblem,weapplylazyobjectinitializationstrategy;Whenreadingfromafuturewritetoareferencetypeandtheobjectisnotyetcreated,thenJPRarbitrarilycreatesanobjectatthespeciclocationontheheap.ThiswillletJPFgowithoutbreakingatanexception.Whenthefuturewrite(i.e.objectcreation)actuallyhappens,itcandetectthattheobjecthasalreadybeencreated. 5.3.5Checkingprogramproperties Assertion.Whencheckingprogramcorrectness,ordinaryJavaassertionsaregenerallyused.InstandardJPF,assertionviolationsarecaughtbyJPF'sgenericNoUncaughtExceptionProperty;Duringmodelchecking,JPFexploresallpossibleinterleavingofinstructionsandthrowsaNoUncaughtExceptionimmediatelyafteranassertionviolationoccurs.JPFstopswhenanexceptionisthrown.JPRontheotherhand,doesnotreportassertionerrorsimmediately.Instead,itdelaysthereportingoftheerroruntiltheendofeachexecutingpath.Thereasonbehinditisthatareadmayrstseeafuturewriteandimposeitwiththevalueitsees,buttheimposedvaluemightnotbejustiedwhenthewriteoccurs(Fig. 3-8 ,line 42 ),orthewritedoesn'texecuteatall(Fig. 3-7 ,line 19 ).Inbothcases,thepathwillbediscarded.Thismeansinapath,areadmayinitiallyseeaninvalidvalueandthewholepathwillbediscardedlateron.InJPR,anassertionerrorwillbedetectedwhenreadingtheinvalidvalue,butnotreporteduntiltheendoftheexecutingpathissuccessfullyreached.Forexample,seetheexecutionsequenceshowninFig. 5-6 .Inthe1stiterationofJPR,Thread2writes1tox.Inthe2nditeration,Thread1readsxas1andimposesthewriteofxinThread2(underlinedaction)towrite1.ThentheassertioninThread2isviolated.Now,JPRdoesnotreporttheerrorherebecausetheentirepathwilleventually 83

PAGE 84

Initially,x==y==0,xandyarenon-volatilevariablesThread1 Thread2 r1=x;read1(future),impose y=r1;write1 r2=y;read1(previous) assert(r2!=1); if(r2==0) x=1; else x=0; Figure5-6. Inthe2nditeration,theassertionisviolated,butthepathwillalsobediscardedlater,becausetheimposedvalueisnotjustied. bediscardedlaterbecauseThread2willnowwrite0(not1)toxinthiscase3(i.e.imposedvalueisnotjustied). ReportScheme.Javaassertstatementcanonlycheckuniversallyheldproperties,butitisinsufcienttocheckpropertiessuchascheckingtheexistenceofsomebehaviorswhichisintensivelyusedin[ 41 ]inreasoningaboutJMM-legalbehaviors.SeetheexampleshowninFig. 2-1 ,assertstatementcancheckpropertiesasr1==r2==42isprohibitedinanyoftheexecutionsbyaddingassert(!(r1==42&&r2==42))atsomepointoftheprogram.UsingComputationTreeLogic(CTL)[ 20 ]formula,itcanbewrittenasAG(:(r1==r2==42)).HereAGmeansalongallpaths,holdsontheentirepath.Butassertionscannotcheckpropertiesliker1==1andr2==2isallowedinsomeexecutions,orEF(r1==r2==42)inCTL.HereEFmeansthereexistsatleastonepaththateventuallyholds.Toovercomethis,weimplementedareportingscheme:attheendofeachlegalexecutingpath,alistofrecordsthatcorrespondtoallthereadactionswillbewrittentoareportle.Eachrecordcontainsthevalueitreadsandthesourcewriteaction'sline 3Notethatinthiscase,thewritewillnotbejustiednomatterwhatkindofactionIDschemeisapplied(scope,occurrence,oroccurrence-val). 84

PAGE 85

number.Itisinthisformat:h[readlinenumber],[threadID],read(eld)=[value]from[linenumberofsourcewrite][threadIDofsourcewrite]iHereisanexample,9Thread)]TJ /F1 11.955 Tf 9.29 0 Td[(0read(ttt1@50.x)=1from22Thread)]TJ /F1 11.955 Tf 9.3 0 Td[(1 .Thepropertiesthatcannotbespeciedbyassertstatementscouldbecheckedbymanuallyanalyzingthegeneratedreportle. 5.4Non-JPFImplementationIssuesInthissection,wediscusssomenon-JPFimplementationissues. 5.4.1DatatypesInx 3.2 ,ValisusedbyWriteSet,ImposeSet,Read,andWrite.WementionedthatValisthedomainofgeneralvalue.Thedatatypecouldbeeitherprimitivetypes(int,long,oat,double,boolean)orreference.InJPR,ValisimplementedastheinterfaceValue.ThevalueofeachdatatypeisaclassthatimplementsValue.TheclassdiagramisshowninFig. 5-7 4.TYPEisanenumerationwitheachelementcorrespondstoadatatype.InJPF,thereferenceofaninstanceistheindexontheheap,soRefValuecanbeviewedasaspecialtypeofint.EachdatatypehasadefaultvalueDEFAULT.ThedefaultvaluesofthedatatypesshowninthegurearelistedinTable 5-2 5.Acompletelistcanbefoundin[ 36 ,x4.5.5].Whenanewinstanceorarrayiscreated,theeldsorthearrayelementswillbeinitializedtothedefaultvaluesofthedatatype.Wewillexplaintheinstance/arraycreationinx 5.4.2 5.4.2ObjectandarraycreationAmongthesynchronizes-withrulesin[ 36 ,x17.4.4],thereisaninterestingruleaboutthewritetothedefaultvalues.ItsaysThewriteofthedefaultvalue(zero,falseornull)toeachvariablesynchronizes-withtherstactionineverythread.Theruleimplies 4Otherdatatypesarenotshowninthegureforbrevity.5InJPF,nullisrepresentedbyinteger-1. 85

PAGE 86

. . . . . . . . . <>Value +type:TYPE +getType():TYPE IntValue +value:int+DEFAULT:int +IntValue(int) BoolValue +value:boolean+DEFAULT:boolean +BoolValue(boolean) FloatValue +value:oat+DEFAULT:oat +FloatValue(oat) DoubleValue +value:double+DEFAULT:double +DoubleValue(double) RefValue +value:int+DEFAULT:int +RefValue(int) . . Figure5-7. ClassDiagramofDataTypes. DataTypeDefaultValue booleanfalseint0oat0.0fdouble0.0dreferencenull Table5-2. DefaultvaluesinJava. thatbeforetheobjectcontainingthevariableisallocated,thereshouldbeawritetothedefaultvalue.Conceptually,atthestartoftheprogram,everyobjectiscreatedwithdefaultvaluewrittentoit.However,thisisnotpracticalforJPFtocapture;beforeactualexecutionoftheprogram,wedon'tknowexactlywhichobjectwillbecreated.ThisrulerequiresspecialtreatmentandthereforeisnotincludedinJMMListeneralgorithm(Figs. 3-7 and 3-8 ). 86

PAGE 87

caseOBJECT/ARRAYCREATED: 66foreacheldoftheobject(orthearrayelement)ddo Createnaction=(naid,init thread,WRITE,d) 68ActionSet ActionSet[naction//addnactiontoactionset letdefbethedefaultvalueofd0sdatatype 70//updateWriteandWriteSetwithdefaultvalue Write(naid) def 72WriteSet(d) WriteSet(d)[f(naid,def)g //updatehbduetodefaultvalueruleofsw 74foreachthreadidttiddo letrstberst.tid==ttid^rst.kind==THREAD START 76HBSet HBSet[f(naid,rst.aid)g caseTHREADSTARTS: 78letthestartedthreadidbetidandidofthethreadthatstartsitbeptid Createaction=(aid,tid,THREAD START,undef)//wedon'tcaretheloc 80ActionSet ActionSet[factiong//addactiontoactionset HBSet f(ThreadLast(ptid),aid)g//updatehbduetothreadstartruleofsw 82ThreadLast(tid)=aid //updatehbduetodefaultvalueruleofsw 84foreachactionnactions.t.naction2ActionSet^naction.tid==init threaddo HBSet HBSet[f(naction.aid,aid)g Figure5-8. Algorithmthathandlesobject/arraycreations,anextensionfromFig. 3-8 InourimplementationofJPR,wemaintainaspecialthreadcalledinit thread.Theactionsofinit threadareallwritestothedefaultvallues.Unlikeotherthreads,init threadisdynamicallyconstructed;Thesetofactionsisnotxed,butkeepsonexpandingwhenanobjectorarrayiscreatedbysomethread.ThedetailedalgorithmisshowninFig. 5-8 .HeretheobjectandarrayinstantiationarerepresentedbyJava'sbytecodenewandnewarrayrespectively.JPFcancapturetheexecutionofthetwo.Uponobject/arraycreation,weloopovertheeldsoftheobjectorthearrayelements,andcreateawriteactionforeachofthem.Thevaluethatassociatedwiththewriteisthedefaultvalueofthecorrespondingdatatype.TheActionSet,Write,andWriteSetareupdatedbecauseofthedefaultwrite.TheHBSetisalsoupdatedbyloopingoverallthestartedthreadsandaddinganhappens-beforeedgefromthedefaultwritetotheTHREAD STARTactionofthatthread.HereTHREAD STARTisaspecialactionkindforthreadstartactions.Itisalsoapairof(t,k,v,u),butthememorylocationvisnotdened. 87

PAGE 88

Besidestheoperationsatobject/arraycreationevent,wealsoneedtotakecareofthreadstartevent.Whenathreadisstarted,wemustloopovertheactionsofinit threadandaddhbedgefromthemtotheTHREAD STARTaction.Also,weneedtoupdatetheActionSet,ThreadLast,aswellastheHBSetduetothethreadstartruleofsynchronizes-withorder. 5.4.3Checkinghappens-beforeconsistencyFortheJPRmetadata,thedatastructuresusedforWriteSet,Write,andReadarehashtables;ActionSetandImposeSetaresimplesetsofelements.ForHBSet,therearemanywaystoimplement.ThedifferencebetweenHBSetandothermetadataisthatHBSetisexpandedbydirecthbrelations,butcheckedbyatransitiveclosure.AndirectwayofimplementingHBSetistomaintainthetransitiveclosureofit.WemayusethekleeneclosureHBSettodenotethetransitiveclosure.Thisimplementationfacilitatesthelookupperformance,butconsumeslargememoryspaces.InJPR,weconstructadirectedacyclicgraph(DAG)whereactionsarenodesandandirectededgebetweentwonodesaiandajimpliesthataihbaj.Whencheckinghappens-beforeconsistency(seeitem 9 ofDenition 3 )betweenanon-volatilereadactionrofvariablevarandanon-volatilewriteactionwwherew=V(r),thegraphistraversedtondpossiblepathsbetweenthetwoactions. i) Thesearchstopswhenwendapathfromrtow,whichindicatesaviolationofforallreadsrofvariablev,r6hbW(r) ii) Thesearchstopswhenwendapathfromwtorthatcontainsanotherintermediatewriteactionw0tothesamevariable,whichindicatesviolationofifW(r)hbwhbrandwwritestovthenW(r)=w.Thetimecomplexitydependsonthepathsearchalgorithmused.Ifusingdepth-rstsearch,thecomplexitywouldbeO(jAj+jEj)wherejAjrepresentsthenumberofactionsandjEjrepresentsthenumberofedges.Notethatthegraphisdynamicandchangesasactionsandedgesareaddedtoit.Happens-beforeconsistencyisfrequentlycheckedsothetimecomplexitydirectlyaffectstheperformanceofJPR. 88

PAGE 89

5.4.4WorkingwithJavaRacenderTheJMMguaranteesthatifaprogramisfreeofdataracesonallofitssequentiallyconsistentexecutions,thenallofitsexecutionsaresequentiallyconsistent.SuchprogramiscalledDRFprogram.InanyexecutionofDRFprograms(Denition 6 ),areadonlyseesthevalueofthemostup-to-datewrite,butnototherwrites(otherpastwritesandfuturewrites).Thisguaranteeisprovedby[ 7 ]andislistedinTheorem 2.1 .ForDRFprograms,becauseitsexecutionsaresequentiallyconsistent,sothestandardJPFissufcienttocarryoutmodelchecking.StandardJPFdoesn'thaveiterations,andrequireslessmemoryspacethanJPRfornotmaintainingmetadata(x 3.2 ).Therefore,ifweknowthataprogramisDRF,thenwemayimprovetheperformancebysimplyrunningstandardJPF.JavaRacender(JRF,nowcalledjpf-racender)[ 45 48 49 ]isatoolthatpreciselyidentiesDRFprograms.IfnodataracesarereportedbyJRF,thentheprogramisDRF.JRFisbasedonJMM'sdenitiononDRF;Ifallsequentiallyconsistentexecutionsoftheprogramarefreeofdataraces[ 60 ],itisaDRFprogram.JRFisastandardextensiontoJPF.Duringitspathexploration,JRFmaintainsaso-calledhsetthatcontainsallthevariablesthatarenotinvolvedinanydataracesinthecurrentSCexecutionsofar.hsetisexpandedorshrunkenaccordingtoJRFoperationalsemantics.Ateachnon-volatileread/writeaction,JRFcheckswhetherthetargetvariableisincludedinthehsetornot.Whenthisconditionholdsforallnon-volatilereadsandwritesinan(SC)execution,theexecutionish-legal.[ 48 ].Ithasbeenprovedthath-legalexecutionsarefreeofdataraces.JRFisprecise.Itdetectsallthedataraceswithoutfalsealarms.WiththepresenceofJRF,wehavethecallingstructureshowninFig. 5-9 .WerstlyrunJRFonthetargetprogramtocheckwhethertheprogramcontainsdataraceornot.IftheprogramisDRF,wesimplyrunstandardJPF;ifnot,thenwerunJPR. 89

PAGE 90

. JRF JPF JPR bytecode DRF :DRF correct?Y=N correct?Y=N Figure5-9. WorkingwithJRF. ThefollowingtwoissuesareaboutthehsetinJRFanditspotentialimprovementsonJPR.WewillshowthattheycannotbeusedinJPR. hsetandWriteSet.InJRF,wecheckdataracewhenexecutingnon-volatilereadorwriteonvariablexinthreadtwithnoracerule:norace(x,t)=x2h(t).Basically,thehsetcontainsthevariablesthatarenotinvolvedinthedataracesofar.BecausewerunJRFbeforeJPR,onemightbelievethatwecouldonlymaintainWriteSetonlyforvariablesthatarenotinhsetforanyexecutionsgeneratedbyJRF,andtreatthevariableswithinhsetasvolatilevariables(i.e.readthemostrecentwrite).However,hsetisdenedunderthecontextofSCmemorymodel.Avariablenotinvolvedinanysequentiallyconsistentexecutionsmaystillberacyinsomesequentiallyinconsistentexecutions. Initially,x=y=z=0Thread1 Thread2 1r1=z; 5r2=y;2if(r1==1) 6z=r2;3x=1; 7r3=x;4y=1; Figure5-10. AnotracyvariableunderSCmayberacyundernon-SC. 90

PAGE 91

SeetheexampleinFig. 5-10 .ThisprogramisnotDRF.UsingJRF,wemaygettwodataracesinvolvingyandz,butxisnotreported.Inanylegalsequentiallyconsistentexecutions,thewritetoxatline3willnotexecute,soxisnotinvolvedindataraces.However,underJMM,thereadofyinline5mayseethefuturewriteinline4toletthewriteofxexecute.Thenxcouldstillbeinvolvedinadatarace.Soxcannotbetreatedasvolatilevariable.Therefore,ifaprogramisdetectedasnon-DRFbyJRF,wemustmaintainWriteSetforallthenon-volatilevariablesintheprogram. hsetandHBSet.BasedonJMM'sdataracedenition(Denition 5 ),weshouldknowallthehappens-beforerelationsinthecurrentexecutionwhencheckingdatarace.TypicallythehbrelationsformaDAGasdiscussedinx 5.4.3 .JRFhowever,getsaroundtheexpensiveconstructionandsearchingofthegraphbyhset.InJRF,eachsynchronizationaddress(volatilevariableormonitor)andthreadhasanhset.Formally,hsetisamappingofh:SynchAddr[Threads!2Addr.Variablesareaddedtohsetbyobjectinstantiation,andremovedfromhsetbynon-volatilewrite.hsetiscopiedbetweenthreadsandvariablesbyreleaseandacquireactions;OnecouldbelievethathsetcouldbeusedinJPRalso.However,hsetanswerswhethertwoactionsareorderedbyhbornot,whichisayesornoquestion.hsetdoesn'tcaretheexacthborderbetweenactions.JPRhoweverneedtoknowtheexacthborderbetweenactionsinordertocheckhappens-beforeconsistency(rule 9 ofDenition 3 ),soasimplesetthatcontainsnon-racyvariablesisnotenough. 91

PAGE 92

CHAPTER6EXPERIENCEANDEVALUATIONInthischapterwepresenttheexperienceandevaluationofJPRanditsalgorithm.Werstlypresentsomebenchmarkexamples.Thereexamplesareusedtoshowthat JPRcangeneratealltheexecutionsthatareallowedbyJMMandcanruleoutforbiddenexecutionstoacertaindegree. JPRcouldbesoundlyusedtoidentifybenigndataraces.Inthesecondsection,welisttheexperimentresultsoftheexamples.WecomparedifferentactionIDschemes,andpointoutcommonbenigndataracepatterns.Finally,weshowthattheideaofJPRisnotrestrictedtoJMM,butcanbefurtherextendedtootherrelaxedmemorymodels.WepresenttherevisedalgorithmforPSO,whichisahardwarememorymodelusedbySPARCsystems,andexplainhowitworks.WealsopresentasimilaralgorithmforTSOinAppendix B 6.1TestSuitesToevaluateJPR,weranitonthreegroupsoftestprograms.Therstgroup,labeledtc1throughtc20arethetestcasesderivedfromtheJMMCausalityTestCases[ 41 ](alsolistedintheAppendix),whichweredesignedtoillustratethepropertiesoftheJMM.Forthese,weoutputthepathsgeneratedbyJPRandcomparethemwiththelegalexecutionsaccordingtoJMM.AlllegalexecutionsweregeneratedbyJPRwithtc5andtc10generatingforbiddenexecutions.tc5istheexampleshowninFig. 4-1 anddiscussedinx 4.2 .tc10issimilartotc5butwithsomebranchconditions.tc14andtc15arenottestedbecausetheyareDRFprogramswhichareidentiedbyJRF,andcanbeanalyzedbystandardJPFinsteadofJPR.TheJavasourcecodeoftc10isshowninFig. 6-1 .[ 41 ]claimsthatr1==r2==1^r3==0isforbiddenunderJMMbecauseofthedataandcontroldependencies;r1andr2cannotbe1unlessr3is1.Thistestcasehasasimilareffectasoftheprogramwithoutbranchconditions.TheexplanationoftheoverapproximationcanbefoundatFig. 4-2 92

PAGE 93

1publicclasstc10f staticintx=0,y=0,z=0;//sharedvariables 3publicstaticvoidmain(Stringargs[])f newThread(newrunnable()f 5publicvoidrun()f intr1=x; 7if(r1==1)y=r1; g 9g).start(); newThread(newrunnable()f 11publicvoidrun()f intr2=y; 13if(r2==1)x=r2; g 15g).start(); newThread(newrunnable()f 17publicvoidrun()f z=1; 19g g).start(); 21newThread(newrunnable()f publicvoidrun()f 23intr3=z; if(r3==1)x=r3; 25g g).start(); 27g g Figure6-1. Javacodeoftestcase10from[ 41 ] Thesecondgroupcontainsmorerealisticexampleswhereassertionswereappliedtotestwhetherthedataraceswerebenign.Theseincludehash(with2-and4-threadversions),hash2,isprime,lazy-b,andbadbit.hashisderivedfromJava'sStringclass.Inhash,thehashCode method(Fig. 6-2 withline 15 deleted)containsaracylazyinitializationofitshash eld;thereadofhash(Line 7 )andthewriteofhash(Line 13 )mayformadatarace.Thisraceisbenignbecauseinalllegalexecutions,eventhesequentiallyinconsistentones,acalltothehashCode methodwillalwaysreturnthecorrecthashcodevalue.Theassertionsappliedinboththe2-threadversionand4-threadversionofhashconrmthisnding. 93

PAGE 94

publicnalclassStringf 2privatenalcharvalue[];//naleldssetinconstructor privatenalintoffset,count; 4privateinthash;//notnal,defaultvalueis0 ... 6publicinthashCode()f inth=hash; 8intlen=count; if(h==0&&len>0)f 10intoff=offset; charval[]=value; 12for(inti=0;i
PAGE 95

publicclassPrimef 2privatebooleanpag[]=newboolean[N]ftrue,true,...g//Nisaninteger ... 4publicbooleanisprime(intv)f intbound=(int)Math.oor(Math.sqrt((double)v))+1; 6for(inti=2;i
PAGE 96

publicclassFibonaccif 2privateintb[]=newint[20]; ... 4publicintcalculateFib(intn)f intb=b[n]; 6if(b==0)f if(n==1jjn==2) 8b=1; else 10b=calculateFib(n)]TJ /F25 10.909 Tf 11.52 0 Td[(1)+calculateFib(n)]TJ /F25 10.909 Tf 11.66 0 Td[(2); b[n]=b; 12g returnb; 14g g Figure6-4. Calculatingbonaccinumberbylazyinitialization. bonaccinumberisguaranteedtobereturnedtothecaller.Applyingassertstatements,JPRdoesn'tdetectviolations.badbitisderivedfrom[ 74 ,x2.6].TheJavaversionoftheprogramislistedinFig. 6-5 .TheclassBadBithasasharedvariableisbadandasharedarraydataArray.TwoworkerthreadsarecallingcheckBadArraymethodatthesametimewitheachthreadcheckingadifferentsectionofdataArray.ThecheckBadArraymethodloopsovertheelementsinthespeciedsectionofdataArray.Ineachloop,itchecksisbadeldtoseeifitissetto1byotherthreads.Ifnot,itcheckstheelementsinthesectionandreturnsassoonasanelementisbad(i.e.1)andassignsisbadto1.Aftertheterminationofthetwothreads,themainthreadchecksisbadtoseeifthereareanybadbitsidentied.Becauseisbadisnotvolatile,thereisadataracebetweenline 17 andline 20 .However,thisdataraceisbenign.Supposeonethreaddoesn'tseetheupdatedvalueofisbad,theonlyeffectwouldbemoreiterations,butintheend,themainthreadalwaysgetsthecorrectisbadvalueafterjoiningoftheworkerthreads.Thethirdgroupcontainssomewell-knownsynchronizationproblems.TheyareallcorrectunderSCmemorymodel,butfailunderJMM.Thisgroupincludesdcl,peterson, 96

PAGE 97

publicclassBadBitf 2privateintisbad=0; privatestaticint[]dataArray=newint[]f0,0,0,0,0,0,0,1,0,0g; 4publicstaticvoidmain(Stringargs[])f Threadt1=newThread(newRunnable()f 6publicvoidrun()fBadBit.checkBadArray(0,4); g); 8Threadt2=newThread(newRunnable()f publicvoidrun()fBadBit.checkBadArray(5,9); 10g); t1.start();t2.start(); 12tryft1.join();t2.join();gcatch(Exceptione)fg assert(isbad==1); 14g publicintcheckBadArray(intstart,intend)f 16for(inti=start;i<=end;i++)f if(isbad==1 )return; 18elsef if(dataArray[i]==1)f 20isbad=1; return; 22g g 24g g 26g Figure6-5. Programchecksifthereisabadbitinanarray. anddekker.AlthoughJPRgeneratesmorebehaviorsthanJMM,whichmeansithasfalsealarmsinidentifyingharmfuldataraces,weshowthatJPR'sidenticationsonthesetestcasesarecorrect.dclistheinfamousdouble-checkedlocking(DCL)idiom[ 9 ]whichattemptstoreducelockingoverheadbylazyinitializationofanobject.Inthetestcase,twothreadscallthegetHelper methodofFoo showninFig. 6-6 .Thereadofhelper(line 7 )isplacedoutsidethesynchronizedblock,whiletheconstructionofhelper(line 10 )isplacedwithinthesynchronizedblock.Thereisadataracebetweenthetwoactions.Supposeatonetime,Thread0isexecutingline 10 whileThread1isexecutingline 7 justbeforeThread0hasnishedconstructionofhelper.ThenThread1detectsthathelperisnot 97

PAGE 98

//Globalvariable 2Foofoo=newFoo(); ... 4classFoof privateHelperhelper=null; 6publicHelpergetHelper()f if(helper==null)f//readhelper 8synchronized(this)f if(helper==null)f 10helper=newHelper();//constructhelper g 12g g 14returnhelper; g 16g classHelperf 18publicintx; publicHelper()fx=10;g 20g classThread0extendsThreadf 22publicvoidrun()f Helperh1=foo.getHelper(); 24assert(h1.x!=0); g 26g classThread1extendsThreadf 28publicvoidrun()f Helperh2=foo.getHelper(); 30assert(h2.x!=0); g 32g Figure6-6. Doublecheckedlocking emptyandreturnsitimmediatelywithoutenteringthesynchronizedblock.Inthiscase,Thread0isactuallyreturningapartiallyconstructedobject,allowingotherthreadstoseeapartiallyconstructedobject.Thisistheunsafepublicationproblem.Tocapturethisbug,weinsertedassertionstocheckifthereferencereturnedfromgetHelper() iscorrectlyconstructedornot(line 24 and 30 );ifcorrectlyconstructed,thexeldofthereferenceshouldnotbe0(theinitialvalue).TosolvetheDCLproblem,helpershouldbedeclaredasvolatile. 98

PAGE 99

//Globalvariables 2booleanag[]=newboolean[]ffalse,falseg; intturn,x=0; 4... classThread0extendsThreadf 6publicvoidrun()f ag[0]=true; 8turn=1; while(ag[1]==true&&turn==1)fg 10x++;//criticalsection ag[0]=false; 12g g 14classThread1extendsThreadf publicvoidrun()f 16ag[1]=true; turn=0; 18while(ag[0]==true&&turn==0)fg x++;//criticalsection 20ag[1]=false; g 22g //mainthread 24Thread0t0=newThread0(); Thread1t1=newThread1(); 26t0.start();t1.start(); tryf 28t0.join();t1.join(); assert(x==2); 30gcatch(Exceptione)fg Figure6-7. Peterson'salgorithm:guaranteesmutualexclusionunderSC,butfailsunderJMM. peterson(Peterson'salgorithm)anddekker(Dekker'salgorithm)areimplementationsoftheclassicmutualexclusionalgorithmswithoutusingvolatiles.Theyguaranteemutualexclusionundersequentialconsistency,butfailinrelaxedmemorymodelssuchasJMM.Peterson'salgorithmisshowninFig. 6-7 .UnderSC,line 29 inThread0ismutuallyexclusivewithline 19 inThread1.Afterterminationofthetwothreads,xshouldalwaysbe2.UndertheJMM,itispossiblethatThread1writesag[1]totrueatrstbutThread0lateronstillreadsag[1]astheoldvaluefalseandhenceskipsthebusywait 99

PAGE 100

(line 9 ).Thenboththreadswillbeexecutingthemutuallyexclusiveregions.Inthiscase,thetwox++willinterferewitheachotherandtheassertion(line 29 )willfail.Assertionsinsertedtochecknon-interferenceinthecriticalsectionsinpetersonfailedasexpected.Dekker'salgorithmwasproposedbyTh.J.Dekker,andispresentedin[ 27 ,x2.1].Itisoneofthefamoussolutionstoguaranteemutualexclusionoftwothreadsexecutingonacritialsectionundersequentialconsistency.ItappliesasimilarbutmorecomplicatedlogictoPeterson'salgorithm(Fig. 6-7 ).Dekker'salgorithmisprovedtobemoreefcientthanPeterson'salgorithm,butcannotbegeneralizedtoprogramswithmorethantwothreads.TheJavaversionofDekker'salgorithmwithassertstatementsisshowninFig. 6-8 .Inthisalgorithm,agarrayandturnaresharedvariablesthatareusedtoguaranteemutualexclusion.Theincrementofxwithinthetwothreadsarecriticalsections.Beforeenteringthecriticalsections,eachthreadperformsacheckonagandturntoseeifitisitsturntoenter.DifferentfromPeterson'salgorithm,Dekker'salgorithmbusywaitsonagandturnininnerandouterloops.Aftertheexecutionofthecriticalsection,therightofentranceishandedtotheotherthread.SameasPeterson'salgorithm,Dekker'salgorithmguaranteesmutualexclusionunderSCmemorymodel,butfailsunderrelaxedmemorymodelssuchasJMMandPSO.InDekker'salgorithm,operationsonagarrayandturnarenotsynchronized.Therearenohappens-beforerelationsbetweenthereadandwriteofthem.Soitispossiblethatathreadreadsstalevaluesandskipsthechecksinlines 8 and 9 ,or 22 and 23 andboththreadswillbeexecutingthecriticalsectionatthesametime.UsingJPR,theassertstatementinline 39 failedasexpected.BesidesDekker'salgorithm,asimilarapproachisLamport'sbakeryalgorithm[ 52 ],whichalsoguaranteesmutualexclusionbybusywaitonsharedarrayschoosingandnumber.Lamport'sbakeryalgorithmdoesn'thavealimitonthenumberofthreads.However,itstillfailsunderJMMbecauseofthelackofhappens-beforerelations. 100

PAGE 101

//Globalvariables 2booleanag[]=newboolean[]ffalse,falseg; intturn,x=0; 4... classThread0extendsThreadf 6publicvoidrun()f ag[0]=true; 8while(ag[1]=1)f if(turn!=0)f 10ag[0]=false; while(turn!=0)fg//busywait 12ag[0]=true; g 14g x++;//criticalsection 16turn=1;ag[0]=false; g 18g classThread1extendsThreadf 20publicvoidrun()f ag[1]=true; 22while(ag[0]=1)f if(turn!=0)f 24ag[1]=false; while(turn!=1)fg//busywait 26ag[1]=true; g 28g x++;//criticalsection 30turn=0;ag[1]=false; g 32g //mainthread 34Thread0t0=newThread0(); Thread1t1=newThread1(); 36t0.start();t1.start(); tryf 38t0.join();t1.join(); assert(x==2); 40gcatch(Exceptione)fg Figure6-8. Dekker'salgorithm:guaranteesmutualexclusionunderSC,butfailsunderJMM. ThepathsinwhichthetestcasesinthethirdgrouphadassertionviolationsarelegalaccordingtoJMMandthereforeweredetectedbyJPRbutarenotexhibitedby 101

PAGE 102

sequentiallyconsistentprograms.StandardJPFcannotdetecttheseproblems.Forthesetestcases,JPRtooklesstimeandexploredfewerstatesthanJPFbecausetheassertionviolationsterminatedJPRbeforethefullstatespaceexplorationwascomplete. 6.2PerformanceandEvaluation #th scope occurrence occurrence-val JPF iter time states mem iter time states mem iter time states mem time state mem tc1 2 3 1.4s 164 15M 3 1.4s 164 15M 3 1.5s 173 15M 0.8s 44 15M tc2 2 3 1.6s 320 15M 3 1.6s 320 15M 3 1.6s 377 15M 0.8s 54 15M tc3 3 3 4.1s 2315 25M 3 4.1s 2315 24M 3 4.7s 2582 25M 0.9s 349 15M tc4 2 3 1.3s 94 15M 3 1.3s 94 15M 3 1.4s 94 15M 0.8s 40 15M tc5* 4 3 11.2s 6326 26M 3 12.3s 6326 26M 3 14.8s 6877 26M 1.2s 1169 15M tc6 2 4 1.6s 161 25M 3 1.4s 125 15M 3 1.4s 125 15M 0.8s 34 15M tc7 2 4 2.2s 496 25M 4 2.2s 496 25M 4 2.3s 557 26M 0.8s 64 15M tc8 2 3 1.6s 148 15M 3 1.4s 148 15M 3 1.4s 156 15M 0.8s 44 15M tc9 3 3 3.0s 1737 15M 3 3.0s 1737 15M 3 3.3s 1929 15M 1.0s 279 15M tc9a 4 3 2.2s 880 15M 3 2.2s 880 15M 3 2.7s 914 15M 0.9s 261 15M tc10* 2 3 5.7s 3233 25M 3 5.8s 3233 25M 3 5.8s 3233 25M 1.0s 477 15M tc11 2 4 3.1s 1147 26M 4 3.2s 1147 26M 4 4.0s 1452 25M 0.9s 95 15M tc12 2 3 1.5s 175 15M 3 1.5s 175 15M 3 1.5s 175 15M 0.8s 63 15M tc13 2 3 1.2s 32 15M 3 1.2s 32 15M 3 1.2s 32 15M 0.8s 24 15M tc16 2 3 1.4s 197 15M 3 1.4s 197 15M 3 1.5s 197 15M 1.0s 46 15M tc17 2 3 1.9s 565 15M 3 1.9s 565 15M 3 1.9s 641 15M 0.8s 72 15M tc18 2 3 1.9s 565 15M 3 1.8s 565 15M 3 2.0s 641 15M 0.8s 72 15M tc19 3 3 5.2s 2205 25M 3 5.6s 2205 25M 3 5.5s 2502 25M 0.9s 381 15M tc20 3 3 5.1s 2205 25M 3 4.9s 2205 25M 3 6.0s 2502 25M 0.9s 381 15M hash 2 3 1.5s 237 15M 3 1.5s 237 15M 3 1.5s 237 15M 0.7s 60 15M hash 4 3 38.3s 12442 33M 3 38.2s 12442 34M 3 38.6s 12442 34M 1.7s 3720 15M hash2 2 3 1.3s 23 15M 3 1.3s 23 15M 3 1.3s 23 15M 0.8s 98 15M isprime 2 3 2.0s 308 15M 3 2.1s 308 15M 3 2.2s 308 23M 0.9s 118 15M lazy-b 2 3 3.1s 280 15M 3 3.1s 280 15M 3 3.2s 280 15M 0.8s 86 15M badbit 2 3 5.6s 1143 26M 3 5.2s 1143 26M 3 5.8s 1143 26M 0.8s 430 15M dcl 2 3 1.1s 22 15M 3 1.2s 22 15M 3 1.2s 22 15M 0.9s 243 15M peterson 2 3 1.5s 83 15M 3 1.5s 83 15M 3 1.5s 83 15M 1.0s 194 15M dekker 2 3 1.3s 24 15M 3 1.2s 24 15M 3 1.2s 24 15M 0.9s 203 15M Figure6-9. ExperimentalresultscomparingtheperformanceofJPRusingActionIDapproachesscope,occurrence,andoccurrence-val,respectively.*meansthatJPRgeneratespathsnotallowedbyJMM. 102

PAGE 103

RepresentativeresultsarelistedinFig. 6-9 .Thecolumnscontainthenumberofthreads,andforeachactionIDapproachdescribedabove,thenumberofiterationsofJPFrequiredtoconverge,thetotaltime,thenumberofstatesvisitedinthenaliteration,andthemaximummemoryconsumed,respectively.ThenalcolumnsindicatetheresourceusageforstandardJPFforcomparisonpurposes.Alltestingwasperformedona2.27GHzIntel(R)Core(TM)i5CPU,4GBmainmemory,with64-bitWindows7operatingsystem,JDK1.6,andJPFversion6.FromFig. 6-9 ,wecanseethatJPRisabletoreasonaboutconcurrentprogramsunderJMM,whilestandardJPFcannot.JPRgeneratesanoverestimationofJMM-legalexecutions(additionalbehaviorsoftc5andtc10).Excepthash2,dcl,peterson,anddekkerwhereJPRcaughtassertionerrorsandterminatedbeforecompleteexploration,JPRgenerallytakeslongertimeandgeneratesmorestatesthanstandardJPFasexpectedduetoJPR'siterativenature,anditsexplorationofmorepathsduetodatanon-determinsms.Eventhe1stiterationtakeslongertimethanstandardJPF.Thisisshownintheexperimenttablein[ 43 ]2.Alsotheaveragetimeperiterationisgenerallylargerthanthetimeofthe1stiteration,that'sbecauseofthemonotoneexpansionoftheWriteSet;morepathsareexploredinthefollowingiterations.TheexperimentsreectthefactorsthataffecttheJPRrunningtime.ThesameasstandardJPF,thenumberofthreadsisamainfactor.Themorethenumberofthreads,themoreschedulingchoicestomakewhendoingstateadvancement.Agoodexampleisthe2-threadhashand4-threadhash.Thealgorithminbothtestcasesarethesameexceptforthenumberofthreads.Theincreaseofthreadsmayresultinanexponentialincreaseoftime.Anotherfactoristhenumberofsharednon-volatilevariables.Themorethenumberofsharedvariables,themoredatachoicesmaybeprocessedbyJPF. 2Thetablewouldbeovercrowdedifthetimeconsumptioninthe1stiterationofJPRisincluded,sothisinformationisnotshowninFig. 6-9 103

PAGE 104

Forexample,tc11has4sharedvariables.Althoughithasonly2threads,ittakesmuchlongertimethantc1andtc2whichhave2sharedvariablesand2threads.TheJavasourcecodeoftc11islistedinFig. 6-10 .Ithastwothreadsand4sharedintegervariablesw,x,y,andzwithinitialvalue0. publicclasstc11f 2staticintw=0,x=0,y=0,z=0;//sharedvariables publicstaticvoidmain(Stringargs[])f 4newThread(newrunnable()f publicvoidrun()f 6intr1=z; w=r1; 8intr2=x; y=r2; 10g g).start(); 12newThread(newrunnable()f publicvoidrun()f 14intr4=w; intr3=y; 16z=r3; x=1; 18g g).start(); 20g g Figure6-10. Javacodeoftestcase11from[ 41 ] JMMcausalitytestcaseswebpage[ 41 ]claimsthatr1==r2==r3==r4==1isalegalbehaviorfortc11underJMM.Thevalue1canbepropagatedtoallthesharedvariables.Becausethereisnobranchconditions,sotheJMMinterpretationsarethesameforscope,occurrence,andoccurrence-val.Thisbehaviorisanexistentialcondition,sowecannotuseassertstatementtoverifyit.Allthepossibleoutcomesoflocalvariablesr1,r2,r3,andr4afterexecutionarelistedinTable 6-1 .ThistableisadirecttranslationofJPR'sreportscheme.Thevaluesreturnedbythereads,aswellasthewriteactiontheyseearelisted.r1==r2==r3==r4==1isthelastrowinthetable. 104

PAGE 105

Table6-1. Listofallthepossibleoutcomesoflocalvariablesr1,r2,r3,andr4afterexecution.TranslatedfromthereportschemeofJPR. r1r1readfromr2r2readfromr3r3readfromr4r4readfrom 10line 2 0line 2 0line 2 0line 2 20line 2 0line 2 0line 9 0line 2 30line 2 0line 2 0line 2 0line 7 40line 2 0line 2 0line 9 0line 7 50line 2 1line 17 0line 2 0line 2 60line 16 0line 2 0line 2 0line 2 70line 16 1line 17 0line 2 0line 2 80line 2 1line 17 1line 9 0line 2 90line 2 1line 17 0line 2 0line 7 100line 2 1line 17 1line 9 0line 7 110line 16 0line 2 0line 9 0line 2 120line 16 0line 2 0line 2 0line 7 130line 16 0line 2 0line 9 0line 7 140line 16 1line 17 0line 2 0line 7 151line 16 1line 17 1line 9 0line 2 161line 16 1line 17 1line 9 1line 7 Let'sanalyzetheiterationsofJPR.Inthe1stiterationofJPR,onlyr2mayseevalue1;Inthe2nditeration,r1,r2,andr3maysee1;Allthelocalvariablesmaysee1inthe3rditeration,andthelastiterationhasthesameresultas3rditerationandJPRconverges.tc11hasadatadependenciesof(inlinenumber) 17 8 9 15 16 6 7 14 .SofromTable 6-1 ,wendthatr1,r3,andr4cannotbe1unlessr2is1.Alsor1canr4cannotbe1unlessr3is1. Initially,A==B==0Thread1 Thread2 r1=A; r2=B;if(r1==1) if(r2==1)B=1; A=1; if(r2==0) A=1; Figure6-11. tc6:r1==r2==1isallowedbyJMMaccordingto[ 41 ]. 105

PAGE 106

. r1=A; if(r1==1) B=1; r2=B; if(r2==1) A=1; if(r2==0) A=1; Figure6-12. DataandcontroldependenciesofFig. 6-11 .r1==r2==1canbegeneratedbyJPRifscopeactionIDschemeisapplied. TheexperimentresultsalsoreectthedifferentinterpretationsbetweenactionIDschemesofscope,occurrence,occurrence-val.Fig. 6-11 showstc6.In[ 41 ],itsaysr1==r2==1isallowedbyJMM.Thisstatementistrueifoccurrenceoroccurrence-valschemesareapplied,butisfalseonscope.Usingscope,thetwoA=1saredifferentactions,soifr2toget1,thenwecannothavethe2ndA=1committed.WhilethetwoA=1sarethesameactionifoccurrenceandoccurrence-valschemesareapplied.Moreinterestingly,althoughr1==r2==1isforbiddenbyJMMifusingscope,JPRcanstillgeneratethisresultasanoverapproximation.Fig. 6-12 explainsthereason.Thesolidarrowsreecttheowofvalue1inthe1stiterationofJPR.Weseethat1canbepropagatedintotheexecutionviathesecondifofThread2.Inthe2nditeration(dashedarrows),r2futurelyread1fromB=1,andtherstifexecutes.Finally,westillgetB=1executed.Viathispath,wecangetr1==r2==1withoutforcingthesecondiftoexecute.Theproblembehindthisisthelackofrelationofimposevaluesbetweeniterations.JPRusesImposeSettoenforcereadfromfuturewrites,butImposeSetisnotpassedbetweeniterations.PassingImposeSetbetweeniterationsrequiresamorecomplicatedalgorithm. 106

PAGE 107

1@NotThreadSafe publicclassUnsafeLazyInitializationf 3privatestaticResourceresource; publicstaticResourcegetInstance()f 5if(resource==null) resource=newResource();//unsafepublication 7returnresource; g 9g Figure6-13. Unsafelazyinitialization. ComparedbetweenactionIDschemes;scope,occurrence,andoccurrence-val,wendthattheirperformanceinJPRissimilarwithregardtotime,thenumberofstates,andmemoryconsumed.occurrence-valslightlygeneratesmorestatesthanscopeandoccurrencebecauseitdistinguishesthevaluesofwriteactions.AlthoughitisstilldifculttoanswerwhichactionIDschemeisbetterthantheothers,werecommendoccurrence.scopehasagoodperformance,butforbidstoomanybehaviorssuchasFigs. 5-1a and 6-11 .occurrence-valallowsmanybehaviors,butgeneratesmorestates,andmakesJMMcausalityrules 4 and 7 redundant.occurrenceontheotherhand,isamorenaturalscheme.Itallowsmostoftheexecutionsthatoccurrence-valallows,andhasagoodperformanceinJPR.UsingJPR,wefoundacommonbenigndataracepattern:thelazyinitialization.Testcaseshash,isprime,lazy-b,andbadbitcontainbenigndataraces,andallappliedlazyinitialization.Lazyinitializationdefersinitializinganobjectuntilitisactuallyneededwhileatthesametimeensuringthatitisinitializedonlyonce.[ 35 ,x2.2]Lazyinitializationfollowsacheck-then-actidiom;Theprogramrstcheckswhetheraeldisinitializedornot,ifnottheninitializeit.Lazyinitializationworkscorrectlyinsingle-threadedprograms,butinmultithreadedJavaprograms,itmaysufferunsafepublicationproblem,whichisadatarace-relatederror.SeetheexampleshowninFig. 6-13 [ 35 ],supposetwothreadsT1andT2arecallinggetInstance method.T1checksthatresourceisnullandinitializeit;T2checksresourceisnotnullandskiptheif.Becausethelackofhappens-before 107

PAGE 108

publicclassConcurrentSkipListMapextendsAbstractMap 2implementsConcurrentNavigableMap,Cloneable,java.io.Serializablef privatestaticnalRandomseedGenerator=newRandom(); 4privatetransientintrandomSeed; ... 6privateintrandomLevel()f intx=randomSeed; 8x=x<<13; x=x>>>17; 10randomSeed =x=x<<5; if((x&0x80000001)!=0) 12return0; intlevel=1; 14while(((x>>>=1)&1)!=0)++level; returnlevel; 16g g Figure6-14. java.util.concurrent.ConcurrentSkipListMap relationbetweentheinitializationofresourceinT1andthereadofitinT2,adataraceisformed.T2maynotgettheup-to-datestatesofresource.DCL(testcasedcl)useslazyinitializationbuthasthesameproblem.Typically,inordertosolvethisproblem,thelazyinitializationmethodshouldbesynchronized.However,ifthelazyinitializationisappliedonvariablesofprimitivetypes,thedataracemightbebenign.Nosynchronizationmechanismsareneededforthesecaess.Inhash(Fig. 6-2 ),hashCode alwayscalculatesthesamehash valuenomatterhowmanythreadsarecallingit.Inisprime(Fig. 6-3 ),thepagarrayisusedtorecordthealreadyidentiedprimenumbers.Itislazilyinitialized,butthemethodalwaysreturnsthecorrectanswer.Thesameaslazy-b(Fig. 6-4 ),thebarrayrecordsthealreadycalculatedbonaccinumbers.Thecorrectresultisguaranteedtobereturned.Alsoinbadbit(Fig. 6-5 ),theisbadeldislazilyinitializedtorecordthealreadyidentiedbadbits.Thefourtestcasesfollowthesamepatthern;thelazilyinitializedvariablesareusedtoimprovetheperformancebyavoidingrecalculations,butarenotaffectingthecorrectnessoftheprogram. 108

PAGE 109

Besideslazyinitializationonprimitivetypedsharedvariables,anothertypeofbenigndataracearisesfromthegenerationofrandomnumber.Thebenigndataracemaylettherandomnumberlessrandom.OneexampleisConcurrentSkipListMapclassinjava.util.concurrentpackage.ThecodesnippetofConcurrentSkipListMapisshowninFig. 6-14 .Thisclasshasanon-volatileeldrandomSeed.MethodrandomLevelperformsareadfromtheoldrandomSeedandassignsrandomSeedanewvalue.IfrandomLevelmethodiscalledbymorethanonethread,therewouldbeadataracebetweenline 7 andline 10 .However,thisdataracedoesn'taffectthecorrectnessofConcurrentSkipListMapoperationssuchasget,put,andremove,butonlyaffectsthetimecostoftheseoperations.ThereasonisthatConcurrentSkipListimplementsatree-likestructuretostorethelist.TheexpectedtimecostofitsoperationsisO(logN).Givenanewelement,randomLevelcalculatesaproperrandomlevelforit.Ifthethreadsdon'tseeupdatesforrandomSeed,thenmorethantwoelementswillbemappedintothesamelevel.Intheworstcase,alltheelementswouldbemappedtoonelevelandthisstructurewouldbedegradedtoalist,butwithoperationsstillperformingcorrectly.Butinreality,theprobabilitywithallthethreadsseeingthedefaultvalueofrandomSeedisverysmall. Table6-2. Latencycomparisononlazy-bbetweennoexplicitsynchronization,AtomicLongarray,andfullysynchronizedmethod. NosynchronizationAtomicarrayExplicitsync 11.178ms1.220ms1.462ms21.185ms1.211ms1.464ms31.182ms1.224ms1.462msAverage1.182ms1.218ms1.463ms 109

PAGE 110

Table 6-2 showsthelatencycomparisononlazy-bbetweennoexplicitsynchronization,atomicinteger/longarray3,andfullysynchronizedmethod.NotethatvolatilekeywordcannotguaranteeDRFforindividualarrayelements,soitisnotincludedinthetable.Eachsynchronizationschemecreates10threadswitheachthreadcalculatingbonaccinumber500.Weruneachschemethreetimestocomparetheaveragelatency.TheexperimentsarecarriedoutonSPARCEnterpriseT5220serverwith60GBmemory,SunOS5.10OS,andJDK1.6.It'seasytoseethattheprogramwithoutanysynchronizationmechanismsrunsthefastest,andthefullysynchronizedmethodmechanismhasthelargestlatency.Thisphenomenonisevenmoreobviousforlargerprograms.Fromthistable,wecanseethattheidenticationofbenigndataraceisveryimportanttoimprovetheperformanceoftheprograms. 6.3ModelCheckingUnderPSOInthissectionweshowthattheideaofkeepinghistoryofwritescanalsobeappliedtomodelcheckprogramsunderotherrelaxedmemorymodels,suchasPSO.PartialStoreOrder(PSO)isdecribedinx 2.1.2 .ItisarelaxedmemorymodelusedbySPARCsystems.ThearchitectureofPSOissimilartoTotalStoreOrder(TSO)(Fig. 2-4 )exceptthateachprocessmaintainsasetofstorebufferswitheachstorebufferassociatedtoamemorylocation.PSOisrelaxed;Becauseofthedelayedwritebackfromstorebuffertothemainmemory,areadmayseeanold,butnotup-to-datevalue.ThemajordifferencebetweenJMMandPSOisthat,inPSO,areadcannotseeawritethathasn'tbeenexecuted,butJMMallowsthis.Inthissense,PSOissimplertomodelthanJMM.WithJPR,weextendedtheWriteSetideatomodelcheckingPSO.JPR'sxedpointstylealgorithmisusedtocollectvaluesthatwouldbewritteninthefuture.Because 3InJava,theoperationsofatomicvariables(AtomicInteger,AtomicLong,AtomicReference,etc.)areallatomic.Atomicvariablesalsoguaranteeshblikevolatilevariables. 110

PAGE 111

PSOdoesn'tallowreadingfromafuturewrite,wedon'tneedtheiterativerunningofJPF.Instead,thePSOmodelcheckercouldbeastandardJPFextensionprojectwhichonlyrunsJPFonce.Also,PSOdoesn'thavehappens-beforerelationsandimposingfuturewrites,soHBSet,ImposeSet,andThreadLastcanberemovedfromthemetadata.ThelistenerstyledPSOmodelcheckingalgorithmislistedinFig. 6-15 .Hereallthemetadataspeciedinx 3.2 areremovedexceptWriteSetandRead: WriteSet:Loc!2AidProcValFlag Read:Aid!AidValDifferentfromJPR,theWriteSetforPSOisisamappingfrommemorylocationloctopairsof(aid,proc,val,ag),whereaidrepresentstheactionID,procistheprocessid,valisthevalueitwritesto,andagisabooleanvariablewhichindicateswhetherthecurrentvalueisinthemainmemoryornot.AnotherdifferenceisthattheWriteSetisnotasimpleset,butmaintainsaproperorderofthewriteactions.TheWriteSethasaproperty:atanytime,thereisatmostonepairinWriteSet(loc)withag=true.Thismeansforavariable,thereshouldbeatmostonevalueplacedinthemainmemory.Becausethereisnofuturewrites,thebooleansignalthatindicatesfuturewriteisremovedfromRead.ThethreebasicoperationsinPSOarestore,load,andfence.ThestorecanbemappedtowriteactioninJava,andloadcanbemappedtoreadaction.ThereisnofenceinJava,butwecanrandomlypickaseldomlyusedstatementtorepresentit.Fig. 6-15 onlyliststheinstructionexecutingevent.ItdealswithothereventsthesameasFig. 3-7 exceptthatthestate=hWriteSet,Readi,andthereisnoGlobalWriteSet.Forstoreaction,thealgorithmsimplyappendsWriteSet(loc)withanewpairwhoseageldisfalse.Thisiscorrespondingtotheplacementinthestorebufferassociatedwiththeprocessandthevariable.Forloadaction,wenon-deterministicallychooseapairfromWriteSet(loc).Thenon-determinismishandledbydatachoicegenerator.Hereareadmayseeavaluevalwrittenbyeitherthesameprocessorsomeotherprocess.If 111

PAGE 112

readingfromthesameprocess,onlythemostup-to-datevaluecanbeseen.Thisvaluemightbestillinthestorebuffer.Readingfromanotherprocessprocjimpliesthat1)thevalueisalreadyplacedinthemainmemory;2)thestorebufferofthereadprocessisempty;and3)allthevalueswrittenbythewritesthatexecutedbeforethewriteofvalinprocjareremovedfromthestorebuffer.Basedontheaboveobservations,ifreadlocfromWriteSetpair(taid,procj,val,ag),theageldissettotrue,meaningthatthevalueiscurrentlyonthememory.Forprocj,allitspairsoflocbeforethewriteofthevaluefromWriteSet(loc)areremoved.Forproci,theprocessoftheread,allitspairsonlocareremovedfromWriteSet(loc).Thismeansthestorebufferofreadprocessonlocisempty.Forallotherprocesses,thepairsonlocwithag=trueareremoved.Thisistoensurethatatanytime,thereshouldonlybeonepaironlocwithag=true.Thefenceoperationensuresthatthemostrecentvaluesofthecallingprocessarewrittentothemainmemory.Foreachvariable,thealgorithmloopsoveritspairsinWriteSet.Allthepairsfromthecallingprocessareremovedexceptthelatestwrite.ThepiHasWritesignalissettotrueifthecallingprocesshasawritetothatvariable.Allthepairsfromotherprocesseswithag=trueareremovedifpiHasWriteistrue.InPSOListener,weuseWriteSettocollectthereadcandidatesjustlikeJMMLis-tener.However,theWriteSetisnotnon-decreasing.SomepairsmayberemovedfromitatLOADandFENCE.Exceptfordatacollection,theWriteSetinPSOListeneralsosimulatesthestorebuffer.ThisisamajordifferencefromJPR.WeimplementedthealgorithmshowninFig. 6-15 asastandardJPFextensionprojectandtestedseveralexamplesonit.Thepeterson'sanddekker'salgorithmsfailedasexpected.Anditdoesn'tgeneratetheresultshowninFig. 2-1 .ThistooltookshortertimethanJPRgenerallybecauseitdoesn'thaveiterationsandhasfewerdatachoices.SimilartoPSO,theTSOcanalsobemodelcheckedusingthisidea,butitrequiresmorerestrictionsonLOAD. 112

PAGE 113

1PSOListener(searchEvent)f switch(searchEvent)f 3......//otherevents caseEXECUTINGACTION: 5Letaction=(aid,proci,kind,loc) switch(kind)f 7caseSTORE(proci,loc,val): WriteSet(loc) WriteSet(loc)[(aid,proci,val,false); 9break; caseLOAD(proci,loc): 11non)]TJ /F31 9.963 Tf 7.75 0 Td[(deterministicallychoosepairT:(taid,procj,val,ag)fromWriteSet(loc) //Readfromsameprocess,onlythemostrecentvalue 13ifproci=procjthen ifTisthelatestwriteactioninprocithen 15Read(aid) (taid,val) //elseignore 17//Readfromdifferentprocess elseifproci6=procjthen 19Read(aid) (taid,val) (taid,procj,val,ag)!(taid,procj,val,true); 21//DeleteallthepairsinfrontofTinprocj foreachT0:(aid0,procj,val0,ag0)infrontofTinWriteSet(loc)do 23WriteSet(loc) WriteSet(loc)nT0 //Deleteallthepairsofproci 25foreachT00:(aid00,proci,val00,ag00)inWriteSet(loc)do WriteSet(loc) WriteSet(loc)nT00 27//Deletethepairsinmainmemory foreachT000:(aid000,prock,v000,true)(k6=i^k6=j)inWriteSet(loc)do 29WriteSet(loc) WriteSet(loc)nT000 break; 31caseFENCE(proci): foreachlocationlocinWriteSetdo 33boolpiHasWrite=false; foreachpairT:(taid,procj,val,ag)fromWriteSet(loc)do 35//Currentprocess:deleteallthepairsexceptthelatestwrite ifproci=procjthen 37ifTisthelatestwriteactiononlocthen (taid,procj,val,ag)!(taid,procj,v,true) 39piHasWrite=true; else 41WriteSet(loc) WriteSet(loc)nT //Otherprocesses:deletethepairsinmainmemory 43elseifproci6=procjthen ifag=true^piHasWrite=truethen 45WriteSet(loc) WriteSet(loc)nT break; 47g break; 49g g Figure6-15. Listener-styledPSOalgorithm. 113

PAGE 114

CHAPTER7RELATEDWORKThischapterpresentssomerelatedworkscontributedbyotherresearchers,andcomparesthemwithourapproach.Ferrara[ 29 ]usedaxedpointformulationtointerpretthehappens-beforememorymodel.Thisworkwasdoneinthecontextofabstractinterpretation,butwasnotimplementedintoarealtool.Botincan,etal.[ 13 ]showedthatthecausalityrequirementsoftheJMMareundecidable.Workhasbeendoneusingvarioustechniquestoverifyprogramsunderrelaxedhardwareandprogramminglanguagememorymodels.JUMBLE[ 31 ]isadynamicanalysissystemthatimplementsanadversarialmemorybykeepingtrackofahistoryofwritestoracyvariables.Whenaracyvariableisread,theadversarialmemoryreturnssomepastvaluethatJMMallowsandislikelytocrashtheprogram.UnlikeJPR,thistooldoesnotconsidernonracyvariablesandcannotsimulatereadingfromafuturewrite,hencecanonlyprovideanunder-approximationofJMM.RELAXER[ 16 ],atwo-phaseanalysistool,employsdynamicanalysisinitsrstphasetodetectracesonSCexecutionsandpredictspotentialhappen-beforecyclesifrununderoneofTSO,PSO,orPSLO.Inthesecondphase,itrunsthetestedprogramundertherelaxedmemorymodelwithacontrolledschedulerthatrealizestheonewithhappen-beforecycletocheckforprogramviolations.JPRcanbeextendedwithasimilarheuristictopreferexploringpathsthatmayendupwithahappen-beforecycles.WealsomentionthatwehaveextendedJPFtoimplementtheTSOandPSOmemorymodels.Whilenotofsignicantpracticalinterest,thesecouldbeimplementedwithoutrequiringiteration,thusgivinganillustrationofthesignicantcomplexityoftheJMM.Burckhardt,AlurandMartin[ 14 ]appliedaSAT-basedboundedvericationmethodtocheckconcurrentdatatypesunderrelaxedmemoryorderingmodelsemployedbymultiprocessorswhileBurckhardtandMusuvathi[ 15 ]describedamonitoralgorithmthat 114

PAGE 115

couldbeimplementedbymodelcheckerstoverifyrelaxedmemorymodelsduetostorebuffers.TheMemSATsystem[ 89 ]systemacceptsatestprogramcontainingassertionsandanaxiomaticspecicationofamemorymodelandthenusesaSATsolvertondatracethatsatisestheassertionsandaxioms,ifthereisone.BoththeoriginalJMMspecication[ 36 ],andthemodiedversionproposedby[ 7 ]werefoundtohavesurprisingresultswhenappliedtotheJMMCausalitytestcases.MemSATisintendedtobeusedwithsmalllitmustestprogramstodebugmemorymodelspecications.Incontrast,JPRisintendedtoreasonaboutprograms.itexploresallpossiblepathsaccordingtotheJMMandreportsanyassertion(programconstrainviolation)violations,whichcanhelptodecidewhethertheracesarebenignornot.JPRcanbeusedwithprogramscontainingobjectinstantiation,loopsandotherfeaturesthatarenotwellsupportedinMemSAT.TheauthorsofJavamemorymodeldevelopedasimplesimulatorfortheJMM[ 58 ]whichappearstobegearedmoretowardsunderstandingthememorymodelthanservingasatoolforprogramanalysis.Deetal.[ 26 ]developedOpMMwhichusesamodelcheckersimilartoJavaPathFinderforstateexploration.IncontrasttoJPR,OpMMisanunderapproximationoftheJMMwherereadactionscanseepastwritesthatoccurbeforeitinasequentiallyconsistentexecution.Asanunderapproximation,OpMMcouldbeusedforbugdetectionofracyprograms,butnotverication. 115

PAGE 116

CHAPTER8CONCLUSIONInthisthesis,wehavedescribedasimplememorymodel,SCmemorymodel,inwhichareadonlyseesthevalueofthemostrecentwrite.SCrestrictsmosthardwareorcompileroptimizationsandtransformations.JMMontheotherhand,isarelaxedmemorymodel.Itallowsareadtoseemorewritessothatmanyoptimizationsandtransformationsareallowed.However,mostmodernmodelcheckersarebasedonSCmemorymodel,sothatunderJMM,theycanonlybeusedtoreasonaboutdata-race-freeprograms(guaranteessequentialconsistency),butnotprogramsthatcontaindataraces.BasedonJMM'sdeclarativerules,wepresentedanewxed-pointsemanticsthatoverapproximatesJMM.Thisapproachrunsthemodelcheckingalgorithminaniterativewaytocomputealeastxedpointofamonotonefunctionthatcanalsogeneratesequentiallyinconsistentexecutions.Wealsoimplementedthesemanticsintoatool,JPR,whichisbuiltontopofJPF.Withthisextension,JPFcanalsobeappliedtothevericationofJavaprogramswithdataraces.WeranJPRonthreegroupsoftestcases;JMMcausalitytestcases,programsthatcontainbenigndataraces,andprogramsthatcontainharmfuldataraces.WefoundthatJPRcangeneratealltheallowedbehaviorsbutcanalsogeneratesomeforbiddenbehaviors.Becauseofthisoverapproximation,JPRcanbesoundlyusedtoidentifybenigndataraces.Fromtheperformanceperspective,JPRgenerallyrunslongertimeandgeneratesmorestatesthanoriginalJPFbecauseofthedatanon-determinismsanditerations.Although,likeanytoolbasedonmodelchecking,state-spaceexplosionisapotentialproblem,wewereabletosuccessfullyusethetooltoshowthatdataracesinsomeexamplesarebenign.Wealsodemonstratedassertionviolationsinsomeprograms,whicharenotdetectablewithoutawarenessoftheJMM.WhenimplementingJPR,wefoundthatanoperationalsemanticsofJMMrequiresmoreprecisedenitionoftheactionIDconcept.Wehaveproposed,implemented, 116

PAGE 117

andempiricallycomparedthreeapproaches(scope,occurrence,andoccurrence-val).Although,drawingaconclusiononwhichoftheseapproacheswouldbethemostappropriateoneisoutsidethescopeofthisthesis,wehopetostartafruitfuldiscussiononthetopic.AlthoughourapproachispresentedinthecontextofJMM,theideaoftheapproachisnotonlyrestrictedtoJMM,butcanbegeneralizedtoothersimplerrelaxedmemorymodelssuchasPSOandTSO.WepresentedthealgorithmforPSOinChapter6.ThedifferencebetweenPSOandJMMisthatPSOonlyallowsreadtoseepastwrites,sothatiterationisnotneededinthealgorithm.Therearedenitelymanyfutureworkstobedone.Onedirectionistheidenticationofpathsthatviolatetheassertions.Thisinformationisveryhelpfultoprogrammerstounderstandthepotentialprogrambugs.Anotherdirectionisidenticationofmorebenigndataracepatterns,andtheautomaticcategorizationofpatternsbyJPR.Also,tohelpalleviatingthestateexplorationproblem,wemayapplyheuristicstoreachpathswithassertionviolationsfaster.Moreover,itwouldbeinterestingtostudyotherrelaxedmemorymodelsandapplytheideatothem.Thismayleadtobetterunderstandingofthosememorymodels. 117

PAGE 118

APPENDIXAJMMCAUSALITYTESTCASESInthisappendix,wepresenttheJMMcausalitytestcaseslistedin[ 41 ].ThesetestcasesareusedtoreasonabouttheperformanceofJPRinChapter 6 .tc1:r1==r2==1isanallowedbehavior. Initially,x==y==0Thread1 Thread2 r1=x; r2=y;if(r10) x=r2;y=1; tc2:r1==r2==r3==1isanallowedbehavior. Initially,x==y==0Thread1 Thread2 r1=x; r3=y;r2=x; x=r3;if(r1==r2) y=1; tc3:r1==r2==r3==1isanallowedbehavior. Initially,x==y==0Thread1 Thread2 Thread3 r1=x; r3=y; x=2;r2=x; x=r3; if(r1==r2) y=1; tc4:r1==r2==1isaprohibitedbehavior. Initially,x==y==0Thread1 Thread2 r1=x; r2=y;y=r1; x=r2; 118

PAGE 119

tc5:r1==r2==1^r3==0isaprohibitedbehavior. Initially,x==y==z==0Thread1 Thread2 Thread3 Thread4 r1=x; r2=y; z=1; r3=z;y=r1; x=r2; x=r3; tc6:r1==r2==1isanallowedbehavior. Initially,x==y==0Thread1 Thread2 r1=x; r2=x;if(r1==1) if(r2==1)y=1; x=1; if(r2==0) x=1; tc7:r1==r2==r3==1isanallowedbehavior. Initially,x==y==z==0Thread1 Thread2 r1=z; r3=y;r2=x; z=r3;y=r2; x=1; tc8:r1==r2==1isanallowedbehavior. Initially,x==y==0Thread1 Thread2 r1=x; r3=y;r2=1+r1*r1-r1; x=r3;y=r2; 119

PAGE 120

tc9:r1==r2==1isanallowedbehavior. Initially,x==y==0Thread1 Thread2 Thread3 r1=x; r3=y; x=2;r2=1+r1*r1-r1; x=r3; y=r2; tc9a:r1==r2==1isanallowedbehavior. Initially,x==2,y==0Thread1 Thread2 Thread3 r1=x; r3=y; x=0;r2=1+r1*r1-r1; x=r3; y=r2; tc10:r1==r2==1^r3==0isaprohibitedbehavior. Initially,x==y==z==0Thread1 Thread2 Thread3 Thread4 r1=x; r2=y; z=1; r3=z;if(r1==1) if(r2==1) if(r3==1)y=1; x=1; x=1; tc11:r1==r2==r3==r4==1isanallowedbehavior. Initially,x==y==z==0Thread1 Thread2 r1=z; r4=w;w=r1; r3=y;r2=x; z=r3;y=r2; x=1; 120

PAGE 121

tc12:r1==r2==r3==1isaprohibitedbehavior. Initially,x==y==0,a[0]==1,a[1]==2Thread1 Thread2 r1=x; r3=y;a[r1]=0; x=r3;r2=a[0]; y=r2; tc13:r1==r2==1isaprohibitedbehavior. Initially,x==y==0Thread1 Thread2 r1=x; r2=y;if(r1==1) if(r2==1)y=1; x=1; tc14:r1==r3==1^r2==0isaprohibitedbehavior. Initially,a==b==y==0,yisvolatileThread1 Thread2 r1=a; dofif(r1==0) r2=y;y=1; r3=b;else gwhile(r2+r3==0);b=1; a=1; 121

PAGE 122

tc15:r0==r1==r3==1^r2==0isaprohibitedbehavior. Initially,a==b==x==y==0;x,yarevolatileThread1 Thread2 Thread3 r0=x; dof x=1;if(r0==1) r2=y; r1=a; r3=b; else gwhile(r2+r3==0); r1=0; a=1; if(r1==0) y=1; else b=1; tc16:r1==2^r2==1isanallowedbehavior. Initially,x==0Thread1 Thread2 r1=x; r2=x;x=1; x=2; tc17:r1==r2==r3==42isanallowedbehavior. Initially,x==y==0Thread1 Thread2 r3=x; r2=y;if(r3!=42) x=r2;x=42; r1=x; y=r1; 122

PAGE 123

tc18:r1==r2==r3==42isanallowedbehavior. Initially,x==y==0Thread1 Thread2 r3=x; r2=y;if(r3==0) x=r2;x=42; r1=x; y=r1; tc19:r1==r2==r3==42isanallowedbehavior. Initially,x==y==0Thread1 Thread2 Thread3 joinThread3 r2=y; r3=x;r1=x; x=r2; if(r3!=42)y=r1; x=42; tc20:r1==r2==r3==42isanallowedbehavior. Initially,x==y==0Thread1 Thread2 Thread3 joinThread3 r2=y; r3=x;r1=x; x=r2; if(r3==0)y=r1; x=42; 123

PAGE 124

APPENDIXBMODELCHECKINGUNDERTSO TSOListener(searchEvent)gf 2switch(searchEvent)f caseEXECUTINGACTION://othereventsnotlisted 4Letaction=(aid,proci,kind,loc) switch(kind)f 6caseSTORE(proci,loc,val): WriteSet WriteSet[(aid,proci,val,false); 8break; caseLOAD(proci,loc): 10non)]TJ /F8 7.97 Tf 6.59 0 Td[(deterministicallychoosepairT=(taid,procj,val,ag)fromWriteSet(loc) ifprocj=procithen//Readfromsameprocess,onlythemostrecentvalue 12ifTisthelatestwriteactioninPithen Read(aid) val 14elseifprocj6=procithen//Readfromdifferentprocess Read(aid) val 16(taid,procj,val,ag)!(taid,procj,valtrue); //i)proci,othervariables: 18//Deleteallpairsbeforelatestwriteonlocexceptmostrecentoneachvariable LetTiloc=(tilaid,proci,u,ag)bethemostrecentwriteinWriteSet(loc)byproci 20foreachvariableloc0(loc06=loc)inWriteSetdo LetTiloc0=(tilpaid,proci,w,ag) 22bethemostrecentwriteonloc0byprocijustbeforeTilocinWriteSet (tilpaid,proci,w,ag)!(tilpaid,proci,w,unknown) 24foreachpairTlocwithproc=procibeforeTiloc0inWriteSet(loc0)do WriteSet(loc0) WriteSet(loc0)nTloc 26//ii)proci,loc:Deleteallthepairsonloc foreachpairTlocwithproc=prociinWriteSet(loc)do 28WriteSet(loc) WriteSet(loc)nTloc //iii)procj,othervar:DeleteallpairsbeforeTexceptlatestoneoneachvar 30foreachvariableloc0(loc06=loc)inWriteSetdo LetTjloc0=(tjlpaid,procj,w,ag) 32bethemostrecentwriteonloc0byprocjjustbeforeTinWriteSet (tjlpaid,procj,w,ag) (tjlpaid,procj,w,unknown) 34foreachpairTloc0withproc=procjbeforeTjloc0inWriteSet(loc0)do WriteSet(loc0) WriteSet(loc0)nTloc0 36//iv)procj,loc:DeleteallthepairsonlocbeforeT foreachpairTlocwithproc=procjinfrontofTinWriteSet(loc)do 38WriteSet(loc) WriteSet(loc)nTloc //v)prock,loc:Deletethepairsinmainmemoryorunknown 40foreachpairTloc2WriteSet(loc)w/proc=prock^ag6=false(k6=i^k6=j)do WriteSet(loc) WriteSet(loc)nTloc 42break; caseFENCE(proci): 44foreachvariablelocinWriteSetdo boolpiHasWrite=false; 46foreachpairT=(taid,procj,v,ag)fromWriteSet(loc)do ifproci=procjthen//proci:deleteallpairsexceptlatestwrite 48ifTisthelatestwriteactiononlocthen (taid,procj,v,ag)!(taid,procj,v,true) 50piHasWrite=true; elseWriteSet(loc) WriteSet(loc)nT 52elseifproci6=procjthen//Otherprocesses:deletepairsinmainmemory if(ag6=false)^piHasWrite=truethen 54WriteSet(loc) WriteSet(loc)nT break; 56g g 58g FigureB-1. TSOalgorithmusingJPF 124

PAGE 125

TSO(TotalStoreOrder)memorymodelisdescribedinx 2.1.2 .TheunderlyingarchitectureisshowninFig. 2-4 .InTSO,processescommunicatewitheachotherbyaccessingthemainsharedmemory.EachprocessisassociatedwithanFIFOqueue,calledstorebuffer.DifferenttoPSO,onlyonestorebufferisassociatedwitheachprocessinTSO.Writestoanyvariablesarewrittentothestorebufferbeforeushingtothemainmemory.TSOisrelaxed.Itallowsareadtoseeanotup-to-datevalue.ButTSOhasmorerestrictionsonreorderingofstatementsthanPSObecauseofthesinglestorebuffer.SimilartoFig. 6-15 ,weproposedaJPFlistener-styledalgorithmforTSO(Fig. B-1 ).ThealgorithmmainlypresentstheoperationsforthethreeTSOoperationsSTORE,LOAD,andFENCE.Themetadatausedinthealgorithmisthesameasthosepresentedinx 6.3 exceptthattheageldofWriteSetpaircanbeunknowninadditiontotrueandfalse.Fig. B-1 isslightlycomplicatedinLOADcasethanFig. 6-15 becauseTSOhasmorerestrictionsthanPSOintermsofthesinglestorebuffer.ThisalgorithmcanbeeasilyimplementedinJPF. 125

PAGE 126

REFERENCES [1] Adve,SaritaV.andHill,MarkD.WeakOrdering-ANewDenitionandSomeImplications.Tech.Rep.TR902,UniversityofWisconsin-Madison,1989. [2] .Weakordering-anewdenition.Proceedingsofthe17thannualinternationalsymposiumonComputerArchitecture.ISCA'90.NewYork,NY,USA:ACM,1990,2. [3] Adve,S.V.andHill,M.D.Auniedformalizationoffourshared-memorymodels.ParallelandDistributedSystems,IEEETransactionson4(1993).6:613. [4] Akers,S.B.BinaryDecisionDiagrams.Computers,IEEETransactionsonC-27(1978).6:509. [5] Alur,RajeevandMartin,MiloM.K.SpecifyingRelaxedMemoryModelsforStateExplorationToolsSela.(EC)2:WorkshoponExplotingConcurrencyEfcientlyandCorrectly.2009. [6] Andrews,GregoryR.Concurrentprogramming:principlesandpractice.RedwoodCity,CA,USA:Benjamin-CummingsPublishingCo.,Inc.,1991. [7] Aspinall,DavidandSevck,Jaroslav.Formalisingjava'sdataracefreeguarantee.Proceedingsofthe20thinternationalconferenceonTheoremprovinginhigherorderlogics.TPHOLs'07.Berlin,Heidelberg:Springer-Verlag,2007,22. [8] .JavaMemoryModelExamples:Good,BadandUgly.TechnicalReportEDI-INF-RR-1121.SchoolofInformatics,UniversityofEdinburgh,2007. [9] Bacon,David,Bloch,Joshua,Bogda,Jeff,Click,Cliff,Haahr,Paul,Lea,Doug,May,Tom,Maessen,Jan-Willem,Manson,Jeremy,Mitchell,JohnD.,Nilsen,Kelvin,Pugh,Bill,andSirer,EminGun.TheDouble-CheckedLockingisBrokenDeclaration.2008.URL http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html [10] Ball,Thomas,Majumdar,Rupak,Millstein,Todd,andRajamani,SriramK.AutomaticpredicateabstractionofCprograms.PLDI01:ProceedingsoftheACMSIGPLAN2001conferenceonProgramminglanguagedesignandimplemen-tation.NewYork,NY,USA:ACM,2001,203. [11] Batty,Mark,Owens,Scott,Sarkar,Susmit,Sewell,Peter,andWeber,Tjark.MathematizingC++concurrency.Proceedingsofthe38thannualACMSIGPLAN-SIGACTsymposiumonPrinciplesofprogramminglanguages.POPL'11.NewYork,NY,USA:ACM,2011,55. [12] Boehm,Hans-J.andAdve,SaritaV.FoundationsoftheC++concurrencymemorymodel.Proceedingsofthe2008ACMSIGPLANconferenceonProgramming 126

PAGE 127

languagedesignandimplementation.PLDI'08.NewYork,NY,USA:ACM,2008,68. [13] Botincan,Matko,Glavan,Paola,andRunje,Davor.VericationofcausalityrequirementsinJavaMemoryModelisundecidable.Proceedingsofthe8thInternationalConferenceonParallelProcessingandAppliedMathematics:PartII.PPAM'09.Berlin,Heidelberg:Springer-Verlag,2010,62. [14] Burckhardt,Sebastian,Alur,Rajeev,andMartin,MiloM.K.BoundedModelCheckingofConcurrentDataTypesonRelaxedMemoryModels:ACaseStudy.Proceedingsofthe18thInternationalConferenceonComputerAidedVerication.2006. [15] Burckhardt,SebastianandMusuvathi,Madanlal.EffectiveProgramVericationforRelaxedMemoryModels.Proceedingsofthe20thInternationalConferenceonComputerAidedVerication.2008. [16] Burnim,Jacob,Sen,Koushik,andStergiou,Christos.Testingconcurrentprogramsonrelaxedmemorymodels.ISSTA.2011,122. [17] Cenciarelli,Pietro,Knapp,Alexander,andSibilio,Eleonora.Thejavamemorymodel:operationally,denotationally,axiomatically.Proceedingsofthe16thEuro-peanconferenceonProgramming.ESOP'07.Berlin,Heidelberg:Springer-Verlag,2007,331. [18] Choi,Jong-Deok,Lee,Keunwoo,Loginov,Alexey,O'Callahan,Robert,Sarkar,Vivek,andSridharan,Manu.Efcientandprecisedataracedetectionformultithreadedobject-orientedprograms.ProceedingsoftheACMSIGPLAN2002ConferenceonProgramminglanguagedesignandimplementation.PLDI'02.NewYork,NY,USA:ACM,2002,258. [19] Christiaens,MarkandDeBosschere,Koen.TRaDe,atopologicalapproachtoon-the-yracedetectioninjavaprograms.Proceedingsofthe2001SymposiumonJavaTMVirtualMachineResearchandTechnologySymposium-Volume1.JVM'01.Berkeley,CA,USA:USENIXAssociation,2001,15. [20] Clarke,E.M.,Emerson,E.A.,andSistla,A.P.Automaticvericationofnite-stateconcurrentsystemsusingtemporallogicspecications.ACMTrans.Program.Lang.Syst.8(1986):244. [21] Clarke,EdmundandEmerson,E.Designandsynthesisofsynchronizationskeletonsusingbranchingtimetemporallogic.LogicsofPrograms.ed.DexterKozen,vol.131ofLectureNotesinComputerScience.SpringerBerlin/Heidelberg,1982.52.10.1007/BFb0025774. [22] Clarke,EdmundM.TheBirthofModelChecking.25YearsofModelChecking.2008,1. 127

PAGE 128

[23] Clarke,EdmundM.,Grumberg,Orna,andLong,DavidE.Modelcheckingandabstraction.ACMTrans.Program.Lang.Syst.16(1994):1512. [24] Cohen,Ernie,Moskal,Michal,Tobies,Stephan,andSchulte,Wolfram.APreciseYetEfcientMemoryModelForC.ElectronicNotesinTheoreticalComputerScience254(2009):85103.Proceedingsofthe4thInternationalWorkshoponSystemsSoftwareVerication(SSV2009). [25] Cousot,PatrickandCousot,Radhia.Abstractinterpretation:auniedlatticemodelforstaticanalysisofprogramsbyconstructionorapproximationofxpoints.Proceedingsofthe4thACMSIGACT-SIGPLANsymposiumonPrinciplesofprogramminglanguages.POPL'77.NewYork,NY,USA:ACM,1977,238. [26] De,Arnab,Roychoudhury,Abhik,andD'Souza,Deepak.JavaMemoryModelawareSoftwareValidation.Proceedingsofthe8thACMSIGPLAN-SIGSOFTworkshoponProgramanalysisforsoftwaretoolsandengineering.2008. [27] Dijkstra,EdsgerW.Cooperatingsequentialprocesses.NewYork,NY,USA:Springer-VerlagNewYork,Inc.,2002,65. [28] Dubois,Michel,Scheurich,Christoph,andBriggs,Faye.Memoryaccessbufferinginmultiprocessors.25yearsoftheinternationalsymposiaonComputerarchitec-ture(selectedpapers).ISCA'98.NewYork,NY,USA:ACM,1998,320. [29] Ferrara,Pietro.Staticanalysisviaabstractinterpretationofthehappens-beforememorymodel.Proceedingsofthe2ndinternationalconferenceonTestsandproofs.TAP'08.Berlin,Heidelberg:Springer-Verlag,2008,116. [30] Flanagan,CormacandFreund,StephenN.Type-basedracedetectionforJava.ProceedingsoftheACMSIGPLAN2000conferenceonProgramminglanguagedesignandimplementation.PLDI'00.NewYork,NY,USA:ACM,2000,219. [31] .Adversarialmemoryfordetectingdestructiveraces.Proceedingsofthe2010ACMSIGPLANconferenceonProgramminglanguagedesignandimplementation.PLDI'10.NewYork,NY,USA:ACM,2010,244. [32] Gamma,Erich,Helm,Richard,Johnson,Ralph,andVlissides,John.Designpatterns:elementsofreusableobject-orientedsoftware.Boston,MA,USA:Addison-WesleyLongmanPublishingCo.,Inc.,1995. [33] Gao,G.R.andSarkar,V.Locationconsistency-anewmemorymodelandcacheconsistencyprotocol.Computers,IEEETransactionson49(2000).8:798. [34] Gharachorloo,Kourosh.MemoryConsistencyModelsforShared-MemoryMultiprocessors.Tech.Rep.CSL-TR-95-685,StanfordUniversity,1995. [35] Goetz,Brian,Peierls,Tim,Bloch,Joshua,Bowbeer,Joseph,Holmes,David,andLea,Doug.JavaConcurrencyinPractice.Addison-Wesley,2006. 128

PAGE 129

[36] Gosling,James,Joy,Bill,Steele,Guy,andBracha,Gilad.Java(TM)LanguageSpecication,The(3rdEdition)(Java(Addison-Wesley)).Addison-WesleyProfessional,2005. [37] Hatcliff,JohnandDwyer,MatthewB.UsingtheBanderaToolSettoModel-CheckPropertiesofConcurrentJavaSoftware.Proceedingsofthe12thInternationalConferenceonConcurrencyTheory.CONCUR'01.London,UK:Springer-Verlag,2001,39. [38] Henzinger,ThomasA.,Jhala,Ranjit,Majumdar,Rupak,andSutre,Gregoire.SoftwarevericationwithBLAST.Proceedingsofthe10thinternationalconfer-enceonModelcheckingsoftware.SPIN'03.Berlin,Heidelberg:Springer-Verlag,2003,235. [39] Hoare,C.A.R.Anaxiomaticbasisforcomputerprogramming.Commun.ACM26(1983):53. [40] Ivancic,F.,Shlyakhter,I.,Gupta,A.,Ganai,M.K.,Kahlon,V.,Wang,Chao,andYang,Zijiang.ModelcheckingCprogramsusingF-Soft.ComputerDesign:VLSIinComputersandProcessors,2005.ICCD2005.Proceedings.2005IEEEInternationalConferenceon.2005,297308. [41] JavaMemoryModelCausalityTestCases.2012.URL http://www.cs.umd.edu/~pugh/java/memoryModel/unifiedProposal/testcases.html [42] JavaPathnder.2012.URL http://babelfish.arc.nasa.gov/trac/jpf [43] Jin,Huafeng,Yavuz-Kahveci,Tuba,andSanders,BeverlyA.JavaPathRelaxer:ExtendingJPFforJMM-AwareModelChecking.TheJavaPathnderWorkshop2011.2011. [44] Jr.,EdmundM.Clarke,Grumberg,Orna,andPeled,DoronA.ModelChecking.TheMITPress,1999. [45] JRF-download.JavaRacender.2012.URL http://babelfish.arc.nasa.gov/trac/jpf/wiki/projects/jpf-racefinder [46] Kahlon,Vineet,Yang,Yu,Sankaranarayanan,Sriram,andGupta,Aarti.Fastandaccuratestaticdata-racedetectionforconcurrentprograms.Proceedingsofthe19thinternationalconferenceonComputeraidedverication.CAV'07.Berlin,Heidelberg:Springer-Verlag,2007,226. 129

PAGE 130

[47] Kebrt,MichalandSery,Ondrej.UnitCheck:UnitTestingandModelCheckingCombined.Proceedingsofthe7thInternationalSymposiumonAutomatedTech-nologyforVericationandAnalysis.ATVA'09.Berlin,Heidelberg:Springer-Verlag,2009,97. [48] Kim,KyungHee,Yavuz-Kahveci,Tuba,andSanders,BeverlyA.PreciseDataRaceDetectioninaRelaxedMemoryModelUsingHeuristic-BasedModelChecking.Proceedingsofthe2009IEEE/ACMInternationalConferenceonAutomatedSoftwareEngineering.ASE'09.Washington,DC,USA:IEEEComputerSociety,2009,495. [49] .JRF-E:usingmodelcheckingtogiveadviceoneliminatingmemorymodel-relatedbugs.ProceedingsoftheIEEE/ACMinternationalconferenceonAutomatedsoftwareengineering.ASE'10.NewYork,NY,USA:ACM,2010,215. [50] Kuperstein,Michael,Vechev,Martin,andYahav,Eran.Partial-coherenceabstractionsforrelaxedmemorymodels.Proceedingsofthe32ndACMSIG-PLANconferenceonProgramminglanguagedesignandimplementation.PLDI'11.NewYork,NY,USA:ACM,2011,187. [51] Lamport,L.HowtoMakeaMultiprocessorComputerThatCorrectlyExecutesMultiprocessPrograms.IEEETrans.Comput.28(1979):690. [52] Lamport,Leslie.AnewsolutionofDijkstra'sconcurrentprogrammingproblem.Commun.ACM17(1974):453. [53] Leungwattanakit,Watcharin,Artho,Cyrille,Hagiya,Masami,Tanabe,Yoshinori,andYamamoto,Mitsuharu.Modelcheckingdistributedsystemsbycombiningcachingandprocesscheckpointing.ASE.2011,103. [54] Lev-Ami,TalandSagiv,Shmuel.TVLA:ASystemforImplementingStaticAnalyses.SAS00:Proceedingsofthe7thInternationalSymposiumonStaticAnalysis.London,UK:Springer-Verlag,2000,280. [55] Lindholm,TimandYellin,Frank.JavaVirtualMachineSpecication.Boston,MA,USA:Addison-WesleyLongmanPublishingCo.,Inc.,1999,2nded. [56] Loiseaux,C.,Graf,S.,Sifakis,J.,Bouajjani,A.,andBensalem,S.Propertypreservingabstractionsforthevericationofconcurrentsystems.Form.MethodsSyst.Des.6(1995):11. [57] LTSA.LTSA-LabelledTransitionSystemAnalyser.2012.URL http://www.doc.ic.ac.uk/ltsa/ [58] Manson,JeremyandPugh,William.TheJavaMemoryModelSimulator.Work-shoponFormalTechniquesforJava-likePrograms,inassociationwithECOOP.2002. 130

PAGE 131

[59] Manson,Jeremy,Pugh,William,andAdve,Sarita.SPECIALPOPLISSUETheJavaMemoryModel.2005. [60] Manson,Jeremy,Pugh,William,andAdve,SaritaV.TheJavamemorymodel.Proceedingsofthe32ndACMSIGPLAN-SIGACTsymposiumonPrinciplesofprogramminglanguages.POPL'05.NewYork,NY,USA:ACM,2005,378. [61] McMillan,KennethL.SymbolicModelChecking.Norwell,MA,USA:KluwerAcademicPublishers,1993. [62] Mehlitz,PeterC.,Tkachuk,Oksana,andUjma,Mateusz.JPF-AWT:ModelcheckingGUIapplications.ASE.2011,584. [63] Merz,Stephan.ModelChecking:ATutorialOverview.Proceedingsofthe4thSummerSchoolonModelingandVericationofParallelProcesses.MOVEP'00.London,UK:Springer-Verlag,2001,3. [64] Mitra,Tulika,Roychoudhury,Abhik,andShen,Qinghua.ImpactofJavaMemoryModelonOut-of-OrderMultiprocessors.Proceedingsofthe13thInternationalConferenceonParallelArchitecturesandCompilationTechniques.PACT'04.Washington,DC,USA:IEEEComputerSociety,2004,99. [65] MRMC.MarkovrewardModelChecker.2012.URL http://www.mrmc-tool.org/trac/ [66] Naik,Mayur,Aiken,Alex,andWhaley,John.EffectivestaticracedetectionforJava.Proceedingsofthe2006ACMSIGPLANconferenceonProgramminglanguagedesignandimplementation.PLDI'06.NewYork,NY,USA:ACM,2006,308. [67] Narayanasamy,Satish,Wang,Zhenghao,Tigani,Jordan,Edwards,Andrew,andCalder,Brad.Automaticallyclassifyingbenignandharmfuldataracesusingreplayanalysis.Proceedingsofthe2007ACMSIGPLANconferenceonProgramminglanguagedesignandimplementation.PLDI'07.NewYork,NY,USA:ACM,2007,22. [68] Nguyen,AnhCuongandKhoo,Siau-Cheng.TowardsAutomationofLTLVericationforJavaPathnder.Proceedingsofthe15thNationalUndergradu-ateResearchOpportunitiesProgrammeCongress.NUROP'10.2010. [69] Nguyen,Dinh-Phuc,Luu,Chung-Tuyen,Truong,Anh-Hoang,andRadics,N.VerifyingImplementationofUMLSequenceDiagramsUsingJavaPathFinder.KnowledgeandSystemsEngineering(KSE),2010SecondInternationalConfer-enceon.2010,194. [70] Nielson,Flemming,Nielson,HanneR.,andHankin,Chris.PrinciplesofProgramAnalysis.Secaucus,NJ,USA:Springer-VerlagNewYork,Inc.,1999. 131

PAGE 132

[71] NuSMV.NuSMV:anewsymbolicmodelchecker.2012.URL http://nusmv.fbk.eu/ [72] O'Callahan,RobertandChoi,Jong-Deok.Hybriddynamicdataracedetection.ProceedingsoftheninthACMSIGPLANsymposiumonPrinciplesandpracticeofparallelprogramming.PPoPP'03.NewYork,NY,USA:ACM,2003,167. [73] On-the-y,LTLModelCheckingwithSPIN.2012.URL http://spinroot.com/spin/whatispin.html [74] oracle.OracleThreadAnalyzer'sUserGuide.2012.URL http://download.oracle.com/docs/cd/E18659_01/html/821-2124/gecqt.html [75] Owens,Scott,Sarkar,Susmit,andSewell,Peter.ABetterx86MemoryModel:x86-TSO.Proceedingsofthe22ndInternationalConferenceonTheoremProvinginHigherOrderLogics.TPHOLs'09.Berlin,Heidelberg:Springer-Verlag,2009,391. [76] Owicki,SusanandGries,David.AnaxiomaticprooftechniqueforparallelprogramsI.ActaInformatica6(1976):319.10.1007/BF00268134. [77] Peterson,GaryL.MythsAbouttheMutualExclusionProblem.Inf.Process.Lett.12(1981).3:115. [78] Pnueli,Amir.Thetemporallogicofprograms.FoundationsofComputerScience,1977.,18thAnnualSymposiumon.1977,46. [79] Pratikakis,Polyvios,Foster,JeffreyS.,andHicks,Michael.LOCKSMITH:context-sensitivecorrelationanalysisforracedetection.Proceedingsofthe2006ACMSIGPLANconferenceonProgramminglanguagedesignandimplementation.PLDI'06.NewYork,NY,USA:ACM,2006,320. [80] Pugh,William.FixingtheJavamemorymodel.ProceedingsoftheACM1999conferenceonJavaGrande.JAVA'99.NewYork,NY,USA:ACM,1999,89. [81] .TheJavamemorymodelisfatallyawed.ConcurrencyandComputation:PracticeandExperience12(2000):445. [82] Roychoudhury,Abhik.FormalReasoningaboutHardwareandSoftwareMemoryModels.Proceedingsofthe4thInternationalConferenceonFormalEngineeringMethods:FormalMethodsandSoftwareEngineering.ICFEM'02.London,UK,UK:Springer-Verlag,2002,423. [83] Savage,Stefan,Burrows,Michael,Nelson,Greg,Sobalvarro,Patrick,andAnderson,Thomas.Eraser:adynamicdataracedetectorformultithreadedprograms.ACMTrans.Comput.Syst.15(1997):391. 132

PAGE 133

[84] SPARCInternational,CORPORATE,Inc.TheSPARCarchitecturemanual:version8.UpperSaddleRiver,NJ,USA:Prentice-Hall,Inc.,1992. [85] .TheSPARCarchitecturemanual(version9).UpperSaddleRiver,NJ,USA:Prentice-Hall,Inc.,1994. [86] Stark,RobertandBorger,Egon.AnASMSpecicationofC#Threadsandthe.NETMemoryModel.AbstractStateMachines2004.AdvancesinTheoryandPractice.eds.WolfZimmermannandBernhardThalheim,vol.3052ofLectureNotesinComputerScience.SpringerBerlin/Heidelberg,2004.38. [87] Starke,P.H.ReachabilityanalysisofPetrinetsusingsymmetries.Syst.Anal.Model.Simul.8(1991):293. [88] Tarski,Alfred.ALattice-TheoreticalFixpointTheoremanditsApplications.PacicJournalofMathematics5(1955).2:285. [89] Torlak,Emina,Vaziri,Mandana,andDolby,Julian.MemSAT:checkingaxiomaticspecicationsofmemorymodels.Proceedingsofthe2010ACMSIGPLANconferenceonProgramminglanguagedesignandimplementation.PLDI'10.NewYork,NY,USA:ACM,2010,341. [90] Valmari,Antti.Stubbornsetsforreducedstatespacegeneration.Proceedingsofthe10thInternationalConferenceonApplicationsandTheoryofPetriNets:AdvancesinPetriNets1990.London,UK:Springer-Verlag,1991,491. [91] Visser,Willem,Havelund,Klaus,Brat,Guillaume,Park,SeungJoon,andLerda,Flavio.ModelCheckingPrograms.AutomatedSoftwareEngineering10(2003):203.10.1023/A:1022920129859. [92] Sevck,JaroslavandAspinall,David.OnValidityofProgramTransformationsintheJavaMemoryModel.Proceedingsofthe22ndEuropeanconferenceonObject-OrientedProgramming.ECOOP'08.Berlin,Heidelberg:Springer-Verlag,2008,27. [93] Yavuz-Kahveci,TubaandBultan,Tevk.ActionLanguageverier:aninnite-statemodelcheckerforreactivesoftwarespecications.Form.MethodsSyst.Des.35(2009):325. [94] Zhang,XinandvanBreugel,F.ModelCheckingRandomizedAlgorithmswithJavaPathFinder.QuantitativeEvaluationofSystems(QEST),2010SeventhInternationalConferenceonthe.2010,157. 133

PAGE 134

BIOGRAPHICALSKETCH HuafengJinreceivedhisbachelar'sdegreeincomputerengineeringatBeijingUniversityofTechnologyinChinainJuly2006.HestartedhisgraduatestudiesinComputerandInformationScienceandEngineeringdepartmentofUniversityofFloridainAugust2006underthesupervisionofDr.BeverlyA.Sanders.Hisresearchinterestisstaticanalysisonconcurrentprogramsbysoftwaremodelchecking. 134