Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of...

32
1 17-214 Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and GUIs Charlie Garrod Josh Bloch

Transcript of Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of...

Page 1: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

1 17-214

PrinciplesofSoftwareConstruction: Objects,Design,andConcurrencyIntroductiontoconcurrencyandGUIsCharlieGarrodJoshBloch

Page 2: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

2 17-214

Administrivia

•  ReadingdueTuesday:UMLandPatterns26.1and26.4•  Homework4aduetonight

–  Homework4afeedbackcomingnextweek

•  Homework4bdueThursday,March5th–  Anaside:testing

Page 3: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

3 17-214

KeyconceptsfromTuesday

•  Internalrepresentationsmatter•  Goodcodeiscleanandconcise•  Goodcodinghabitsmatter

Page 4: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

4 17-214

Keyconceptsfromyesterday'srecitation

•  Discoveringdesignpatterns•  Observerdesignpattern

Page 5: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

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…

Page 6: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

6 17-214

Today

•  Theobserverpattern•  Introductiontoconcurrency•  IntroductiontoGUIs

Page 7: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

7 17-214

Athreadisathreadofexecution

•  Multiplethreadsinthesameprogramconcurrently•  Threadssharethesamememoryaddressspace

–  Changesmadebyonethreadmaybereadbyothers

•  Multithreadedprogramming–  Alsoknownasshared-memorymultiprocessing

Page 8: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

8 17-214

Threadsvs.processes

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

Page 9: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

9 17-214

Reasonstousethreads

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

Page 10: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

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();}}

Page 11: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

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();}}

Page 12: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

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();}}

Page 13: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

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

Page 14: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

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

Page 15: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

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;}

Page 16: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

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);}

Page 17: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

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));}

Page 18: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

18 17-214

Cryptarithmgenerationperformance

NumberofThreads Secondstorun1 22.02 13.53 11.74 10.8

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

Page 19: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

19 17-214

Sharedmutablestaterequiressynchronization

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

Page 20: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

20 17-214

Thechallengeofsynchronization

•  Notenoughsynchronization:safetyfailure–  Incorrectcomputation

•  Toomuchsynchronization:livenessfailure–  Possibly:Nocomputationatall

Page 21: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

21 17-214

Synchronizationinthecryptarithmexample

•  Howdidweavoidsyncinmultithreadedcryptarithmgenerator?•  Embarrassinglyparallelizablecomputation•  Eachthreadisentirelyindependentoftheothers

–  Theysolvedifferentcryptarithms…–  Andwriteresultstodifferentarrayelements

•  Nosharedmutablestatetospeakof–  Mainthreadimplicitlysynchronizeswithworkersusingjoin

Page 22: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

22 17-214

Today

•  Theobserverpattern•  Introductiontoconcurrency•  IntroductiontoGUIs

Page 23: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

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) }

Page 24: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

24 17-214

ExamplesofeventsinGUIs

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

•  Apacketarrivesfromawebservice,connectiondrops,…•  Systemshutdown,…

Page 25: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

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);

}

Page 26: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

26 17-214

Blockinginteractionswithusers

Game PlayerDealer

newGame

addCards

addCards

getAction

action

[action==hit]addCard

blocking execution

Page 27: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

27 17-214

Interactionswithusersthroughevents

•  Donotblockwaitingforuserresponse•  Instead,reacttouserevents

Game PlayerDealer

newGame

addCards

addCards

hit

addCard

Page 28: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

28 17-214

GUIs:Tobecontinued…

Page 29: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and

29 17-214

Paperslidesfromlecturearescannedbelow..

Page 30: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and
Page 31: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and
Page 32: Principles of Software Construction: Objects, …charlie/courses/17-214/2020...Principles of Software Construction: Objects, Design, and Concurrency Introduction to concurrency and