principles of software construction: objects, …charlie/courses/17-214/2020...principles of...

Post on 20-Jun-2020

12 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1 17-214

PrinciplesofSoftwareConstruction: Objects,Design,andConcurrencyIntroductiontoconcurrencyandGUIsCharlieGarrodJoshBloch

2 17-214

Administrivia

•  ReadingdueTuesday:UMLandPatterns26.1and26.4•  Homework4aduetonight

–  Homework4afeedbackcomingnextweek

•  Homework4bdueThursday,March5th–  Anaside:testing

3 17-214

KeyconceptsfromTuesday

•  Internalrepresentationsmatter•  Goodcodeiscleanandconcise•  Goodcodinghabitsmatter

4 17-214

Keyconceptsfromyesterday'srecitation

•  Discoveringdesignpatterns•  Observerdesignpattern

5 17-214

Observerpattern(a.k.a.publish/subscribe)

•  Problem:Mustnotifyotherobjects(observers)withoutbecomingdependentontheobjectsreceivingthenotification

•  Solution:Defineasmallinterfacetodefinehowobserversreceiveanotification,andonlydependontheinterface

•  Consequences:–  Loosecouplingbetweenobserversandthesourceofthenotifications–  Notificationscancauseacascadeeffect

See edu.cmu.cs.cs214.rec06.alarmclock.AlarmListener…

6 17-214

Today

•  Theobserverpattern•  Introductiontoconcurrency•  IntroductiontoGUIs

7 17-214

Athreadisathreadofexecution

•  Multiplethreadsinthesameprogramconcurrently•  Threadssharethesamememoryaddressspace

–  Changesmadebyonethreadmaybereadbyothers

•  Multithreadedprogramming–  Alsoknownasshared-memorymultiprocessing

8 17-214

Threadsvs.processes

•  Threadsarelightweight;processesareheavyweight•  Threadsshareaddressspace;processesdon't•  Threadsrequiresynchronization;processesdon't•  It'sunsafetokillthreads;safetokillprocesses

9 17-214

Reasonstousethreads

•  Performanceneededforblockingactivities•  Performanceonmulti-coreprocessors•  Naturalconcurrencyinthereal-world•  Existingmulti-threaded,managedrun-timeenvironments

10 17-214

Asimplethreadsexample

publicinterfaceRunnable{//java.lang.Runnablepublicvoidrun();}publicstaticvoidmain(String[]args){intn=Integer.parseInt(args[0]);//Numberofthreads;Runnablegreeter=newRunnable(){publicvoidrun(){System.out.println("Himom!");}};for(inti=0;i<n;i++){newThread(greeter).start();}}

11 17-214

Asimplethreadsexample

publicinterfaceRunnable{//java.lang.Runnablepublicvoidrun();}publicstaticvoidmain(String[]args){intn=Integer.parseInt(args[0]);//Numberofthreads;Runnablegreeter=()->System.out.println("Himom!");for(inti=0;i<n;i++){newThread(greeter).start();}}

12 17-214

Asimplethreadsexample

publicinterfaceRunnable{//java.lang.Runnablepublicvoidrun();}publicstaticvoidmain(String[]args){intn=Integer.parseInt(args[0]);//Numberofthreads;for(inti=0;i<n;i++){newThread(()->System.out.println("Himom!")).start();}}

13 17-214

Aside:AnonymousinnerclassscopeinJava

publicinterfaceRunnable{//java.lang.Runnablepublicvoidrun();}publicstaticvoidmain(String[]args){intn=Integer.parseInt(args[0]);//Numberofthreads;for(inti=0;i<n;i++){newThread(()->System.out.println("T"+i)).start();}}

won't compile because i mutates

14 17-214

Aside:AnonymousinnerclassscopeinJava

publicinterfaceRunnable{//java.lang.Runnablepublicvoidrun();}publicstaticvoidmain(String[]args){intn=Integer.parseInt(args[0]);//Numberofthreads;for(inti=0;i<n;i++){intj=i;//junchangingwithineachloopnewThread(()->System.out.println("T"+j)).start();}}

j is effectively final

15 17-214

Example:generatingcryptarithms

staticList<String>cryptarithms(String[]words,intstart,intend){List<String>result=newArrayList<>();String[]tokens=newString[]{"","+","","=",""};//Checkifeachadjacenttripleinwordsisa"good"cryptarithmfor(inti=start;i<end-2;i++){tokens[0]=words[i];tokens[2]=words[i+1];tokens[4]=words[i+2];try{Cryptarithmc=newCryptarithm(tokens);if(c.solve().size()==1)result.add(c.toString());//Wefounda"good"one}catch(IllegalArgumentExceptione){//toomanylettersincryptarithm;ignore}}returnresult;}

16 17-214

Single-threadeddriver

publicstaticvoidmain(String[]args){Instantstart=Instant.now();List<String>cryptarithms=cryptarithms(words,0,words.length);Instantend=Instant.now();Durationtime=Duration.between(start,end);System.out.printf("Time:%d%nms”,time.toMillis());

System.out.println(cryptarithms);}

17 17-214

Multithreadeddriver

publicstaticvoidmain(String[]args)throwsInterruptedException{intn=Integer.parseInt(args[0]);//NumberofthreadsInstantstartTime=Instant.now();intwordsPerThread=words.length/n;Thread[]threads=newThread[n];Object[]results=newObject[n];for(inti=0;i<n;i++){//Createthethreadsintstart=i==0?0:i*wordsPerThread-2;intend=i==n-1?words.length:(i+1)*wordsPerThread;intj=i;//Onlyconstantscanbecapturedbylambdasthreads[i]=newThread(()->{results[j]=cryptarithms(words,start,end);});}for(Threadt:threads)t.start();for(Threadt:threads)t.join();InstantendTime=Instant.now();Durationtime=Duration.between(start,end);System.out.printf("Time:%d%nms”,time.toMillis());System.out.println(Arrays.toString(results));}

18 17-214

Cryptarithmgenerationperformance

NumberofThreads Secondstorun1 22.02 13.53 11.74 10.8

Generatingallcryptarithmsfromacorpusof344words• Testallconsecutive3-wordsequences(342possibilities)• Testmachineiscrappyoldlaptop(2cores,4hyperthreads)• Thesenumbersareat-bestapproximate

19 17-214

Sharedmutablestaterequiressynchronization

•  Threebasicchoices:1.   Don'tmutate:shareonlyimmutablestate2.   Don'tshare:isolatemutablestateinindividualthreads3.  Ifyoumustsharemutablestate:synchronizeproperly

20 17-214

Thechallengeofsynchronization

•  Notenoughsynchronization:safetyfailure–  Incorrectcomputation

•  Toomuchsynchronization:livenessfailure–  Possibly:Nocomputationatall

21 17-214

Synchronizationinthecryptarithmexample

•  Howdidweavoidsyncinmultithreadedcryptarithmgenerator?•  Embarrassinglyparallelizablecomputation•  Eachthreadisentirelyindependentoftheothers

–  Theysolvedifferentcryptarithms…–  Andwriteresultstodifferentarrayelements

•  Nosharedmutablestatetospeakof–  Mainthreadimplicitlysynchronizeswithworkersusingjoin

22 17-214

Today

•  Theobserverpattern•  Introductiontoconcurrency•  IntroductiontoGUIs

23 17-214

Event-basedprogramming

•  Styleofprogrammingwherecontrol-flowisdrivenby(usuallyexternal)events

public void performAction(ActionEvent e) { List<String> lst = Arrays.asList(bar); foo.peek(42) }

public void performAction(ActionEvent e) { bigBloatedPowerPointFunction(e); withANameSoLongIMadeItTwoMethods(e); yesIKnowJavaDoesntWorkLikeThat(e); }

public void performAction(ActionEvent e) { List<String> lst = Arrays.asList(bar); foo.peek(40) }

24 17-214

ExamplesofeventsinGUIs

•  Userclicksabutton,pressesakey•  Userselectsanitemfromalist,anitemfromamenu•  Mousehoversoverawidget,focuschanges•  Scrolling,mousewheelturned•  Resizingawindow,hidingawindow•  Draganddrop

•  Apacketarrivesfromawebservice,connectiondrops,…•  Systemshutdown,…

25 17-214

Blockinginteractionwithcommand-lineinterfaces

Scannerinput=newScanner(System.in);while(questions.hasNext()){

Questionq=question.next();System.out.println(q.toString());Stringanswer=input.nextLine();q.respond(answer);

}

26 17-214

Blockinginteractionswithusers

Game PlayerDealer

newGame

addCards

addCards

getAction

action

[action==hit]addCard

blocking execution

27 17-214

Interactionswithusersthroughevents

•  Donotblockwaitingforuserresponse•  Instead,reacttouserevents

Game PlayerDealer

newGame

addCards

addCards

hit

addCard

28 17-214

GUIs:Tobecontinued…

29 17-214

Paperslidesfromlecturearescannedbelow..

top related