principles of software construction: objects, …2019/11/05 · 17-214 2 administrivia • homework...
TRANSCRIPT
![Page 1: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/1.jpg)
1 17-214
PrinciplesofSoftwareConstruction: Objects,Design,andConcurrencyPart3:ConcurrencyIntroductiontoconcurrency:ConcurrencychallengesCharlieGarrodChrisTimperley
![Page 2: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/2.jpg)
2 17-214
Administrivia
• Homework5adue9a.m.tomorrow• MidtermexamavailableonGradescope
– RegraderequestsdueMonday,18November
• Readingduetoday:– JavaConcurrencyinPractice,Sections11.3and11.4
![Page 3: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/3.jpg)
3 17-214
Winteriscomingdiscussion
![Page 4: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/4.jpg)
4 17-214
KeyconceptsfromlastTuesday
![Page 5: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/5.jpg)
5 17-214
Aconcurrencybugwithaneasyfix:
publicclassBankAccount{privatelongbalance;publicBankAccount(longbalance){this.balance=balance;}staticsynchronizedvoidtransferFrom(BankAccountsource,BankAccountdest,longamount){source.balance-=amount;dest.balance+=amount;}publicsynchronizedlongbalance(){returnbalance;}}
![Page 6: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/6.jpg)
6 17-214
ConcurrencycontrolwithJava'sintrinsiclocks
• synchronized(lock){…}– Synchronizesentireblockonobjectlock;cannotforgettounlock– Intrinsiclocksareexclusive:Onethreadatatimeholdsthelock– Intrinsiclocksarereentrant:Athreadcanrepeatedlygetsamelock
• synchronizedonaninstancemethod– Equivalenttosynchronized(this){…}forentiremethod
• synchronizedonastaticmethodinclassFoo– Equivalenttosynchronized(Foo.class){…}forentiremethod
![Page 7: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/7.jpg)
7 17-214
Atomicity
• Anactionisatomicifitisindivisible– Effectively,ithappensallatonce
• Noeffectsoftheactionarevisibleuntilitiscomplete• Nootheractionshaveaneffectduringtheaction
• InJava,integerincrementisnotatomic
i++;
1. Load data from variable i
2. Increment data by 1
3. Store data to variable i
is actually
![Page 8: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/8.jpg)
8 17-214
Yetanotherexample:cooperativethreadtermination
publicclassStopThread{privatestaticbooleanstopRequested;publicstaticvoidmain(String[]args)throwsException{ThreadbackgroundThread=newThread(()->{while(!stopRequested)/*Dosomething*/;});backgroundThread.start();TimeUnit.SECONDS.sleep(42);stopRequested=true;}}
![Page 9: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/9.jpg)
9 17-214
Whatwentwrong?
• Intheabsenceofsynchronization,thereisnoguaranteeastowhen,ifever,onethreadwillseechangesmadebyanother
• JVMscananddoperformthisoptimization:while(!done)/*dosomething*/;
becomes:if(!done)while(true)/*dosomething*/;
Process
Thread
Copy
Thread
Copy
Memory
![Page 10: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/10.jpg)
10 17-214
Today
• Midtermexam2recap• MorebasicconcurrencyinJava
– Somechallengesofconcurrency
• Concurrencypuzzlers• Stillcomingsoon:
– Higher-levelabstractionsforconcurrency– Programstructureforconcurrency– Frameworksforconcurrentcomputation
![Page 11: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/11.jpg)
11 17-214
Alivenessproblem:poorperformance
publicclassBankAccount{privatelongbalance;publicBankAccount(longbalance){this.balance=balance;}staticsynchronizedvoidtransferFrom(BankAccountsource,BankAccountdest,longamount){source.balance-=amount;dest.balance+=amount;}publicsynchronizedlongbalance(){returnbalance;}}
![Page 12: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/12.jpg)
12 17-214
Alivenessproblem:poorperformance
publicclassBankAccount{privatelongbalance;publicBankAccount(longbalance){this.balance=balance;}staticvoidtransferFrom(BankAccountsource,BankAccountdest,longamount){synchronized(BankAccount.class){source.balance-=amount;dest.balance+=amount;}}publicsynchronizedlongbalance(){returnbalance;}}
![Page 13: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/13.jpg)
13 17-214
Aproposedfix?:locksplitting
publicclassBankAccount{privatelongbalance;publicBankAccount(longbalance){this.balance=balance;}staticvoidtransferFrom(BankAccountsource,BankAccountdest,longamount){synchronized(source){synchronized(dest){source.balance-=amount;dest.balance+=amount;}}}…}
![Page 14: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/14.jpg)
14 17-214
Alivenessproblem:deadlock
• Apossibleinterleavingofoperations:– bugsThreadlocksthedaffyaccount– daffyThreadlocksthebugsaccount– bugsThreadwaitstolockthebugsaccount…– daffyThreadwaitstolockthedaffyaccount…
![Page 15: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/15.jpg)
15 17-214
Alivenessproblem:deadlock
publicclassBankAccount{privatelongbalance;publicBankAccount(longbalance){this.balance=balance;}staticvoidtransferFrom(BankAccountsource,BankAccountdest,longamount){synchronized(source){synchronized(dest){source.balance-=amount;dest.balance+=amount;}}}…}
![Page 16: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/16.jpg)
16 17-214
Avoidingdeadlock
• Thewaits-forgraphrepresentsdependenciesbetweenthreads– Eachnodeinthegraphrepresentsathread– AnedgeT1->T2representsthatthreadT1iswaitingforalockT2owns
• Deadlockhasoccurrediffthewaits-forgraphcontainsacycle• Onewaytoavoiddeadlock:lockingprotocolsthatavoidcycles
ab
c
d
f
e
h
g
i
![Page 17: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/17.jpg)
17 17-214
Avoidingdeadlockbyorderinglockacquisition
publicclassBankAccount{privatelongbalance;privatefinallongid=SerialNumber.generateSerialNumber();
publicBankAccount(longbalance){this.balance=balance;}
staticvoidtransferFrom(BankAccountsource,BankAccountdest,longamount){BankAccountfirst=source.id<dest.id?source:dest;BankAccountsecond=first==source?dest:source;synchronized(first){synchronized(second){source.balance-=amount;dest.balance+=amount;}}}…
![Page 18: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/18.jpg)
18 17-214
Anothersubtleproblem:Thelockobjectisexposed
publicclassBankAccount{privatelongbalance;privatefinallongid=SerialNumber.generateSerialNumber();
publicBankAccount(longbalance){this.balance=balance;}
staticvoidtransferFrom(BankAccountsource,BankAccountdest,longamount){BankAccountfirst=source.id<dest.id?source:dest;BankAccountsecond=first==source?dest:source;synchronized(first){synchronized(second){source.balance-=amount;dest.balance+=amount;}}}…
![Page 19: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/19.jpg)
19 17-214
Aneasyfix:Useaprivatelock
publicclassBankAccount{privatelongbalance;privatefinallongid=SerialNumber.generateSerialNumber();privatefinalObjectlock=newObject();publicBankAccount(longbalance){this.balance=balance;}
staticvoidtransferFrom(BankAccountsource,BankAccountdest,longamount){BankAccountfirst=source.id<dest.id?source:dest;BankAccountsecond=first==source?dest:source;synchronized(first.lock){synchronized(second.lock){source.balance-=amount;dest.balance+=amount;}}}…
![Page 20: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/20.jpg)
20 17-214
Concurrencyandinformationhiding
• Encapsulateanobject'sstate:Easiertoimplementinvariants– Encapsulatesynchronization:Easiertoimplementsynchronizationpolicy
![Page 21: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/21.jpg)
21 17-214
Anaside:JavaConcurrencyinPracticeannotations
@ThreadSafepublicclassBankAccount{@GuardedBy("lock")privatelongbalance;privatefinallongid=SerialNumber.generateSerialNumber();privatefinalObjectlock=newObject();publicBankAccount(longbalance){this.balance=balance;}
staticvoidtransferFrom(BankAccountsource,BankAccountdest,longamount){BankAccountfirst=source.id<dest.id?source:dest;BankAccountsecond=first==source?dest:source;synchronized(first.lock){synchronized(second.lock){source.balance-=amount;dest.balance+=amount;}…
![Page 22: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/22.jpg)
22 17-214
Anaside:JavaConcurrencyinPracticeannotations
• @ThreadSafe• @NotThreadSafe• @GuardedBy• @Immutable
![Page 23: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/23.jpg)
23 17-214
Today
• Midtermexam2recap• MorebasicconcurrencyinJava
– Somechallengesofconcurrency
• Concurrencypuzzlers• Stillcomingsoon:
– Higher-levelabstractionsforconcurrency– Programstructureforconcurrency– Frameworksforconcurrentcomputation
![Page 24: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/24.jpg)
24 17-214
Puzzler:“RacyLittleNumber”
![Page 25: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/25.jpg)
25 17-214
Puzzler:“RacyLittleNumber”
importorg.junit.Test;importstaticorg.junit.Assert.assertEquals;publicclassLittleTest{intnumber;@Testpublicvoidtest()throwsInterruptedException{number=0;Threadt=newThread(()->{assertEquals(2,number);});number=1;t.start();number++;t.join();}}
![Page 26: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/26.jpg)
26 17-214
Howoftendoesthistestpass?
importorg.junit.Test;importstaticorg.junit.Assert.assertEquals;publicclassLittleTest{intnumber;@Testpublicvoidtest()throwsInterruptedException{number=0;Threadt=newThread(()->{assertEquals(2,number);});number=1;t.start();number++;t.join();}}
(a)Italwaysfails(b)Itsometimespasses(c)Italwayspasses(d)Italwayshangs
![Page 27: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/27.jpg)
27 17-214
Howoftendoesthistestpass?
(a)Italwaysfails(b)Itsometimespasses(c)Italwayspasses–butittellsusnothing(d)ItalwayshangsJUnitdoesn’tseeassertionfailuresinotherthreads
![Page 28: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/28.jpg)
28 17-214
Anotherlook
importorg.junit.*;importstaticorg.junit.Assert.*;publicclassLittleTest{intnumber;@Testpublicvoidtest()throwsInterruptedException{number=0;Threadt=newThread(()->{assertEquals(2,number);//JUnitneverseestheexception!});number=1;t.start();number++;t.join();}}
![Page 29: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/29.jpg)
29 17-214
Howdoyoufixit?(1)
//KeeptrackofassertionfailuresduringtestvolatileExceptionexception;volatileErrorerror;//Triggerstestcasefailureifanythreadassertsfailed@AfterpublicvoidtearDown()throwsException{if(error!=null)throwerror;if(exception!=null)throwexception;}
![Page 30: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/30.jpg)
30 17-214
Howdoyoufixit?(2)
Threadt=newThread(()->{try{assertEquals(2,number);}catch(Errore){error=e;}catch(Exceptione){exception=e;}});*YMMV(It’saracecondition)
Nowitsometimespasses*
![Page 31: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/31.jpg)
31 17-214
Themoral
• JUnitdoesnotwell-supportconcurrenttests– Youmightgetafalsesenseofsecurity
• Concurrentclientsbeware…
![Page 32: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/32.jpg)
32 17-214
Puzzler:“PingPong”
publicclassPingPong{publicstaticsynchronizedvoidmain(String[]a){Threadt=newThread(()->pong());t.run();System.out.print("Ping");}privatestaticsynchronizedvoidpong(){System.out.print("Pong");}}
![Page 33: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/33.jpg)
33 17-214
Whatdoesitprint?
publicclassPingPong{publicstaticsynchronizedvoidmain(String[]a){Threadt=newThread(()->pong());t.run();System.out.print("Ping");}privatestaticsynchronizedvoidpong(){System.out.print("Pong");}}
(a)PingPong(b)PongPing(c)Itvaries
![Page 34: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/34.jpg)
34 17-214
Whatdoesitprint?
(a)PingPong(b)PongPing(c)ItvariesNotamultithreadedprogram!
![Page 35: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/35.jpg)
35 17-214
Anotherlook
publicclassPingPong{publicstaticsynchronizedvoidmain(String[]a){Threadt=newThread(()->pong());t.run();//Aneasytypo!System.out.print("Ping");}privatestaticsynchronizedvoidpong(){System.out.print("Pong");}}
![Page 36: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/36.jpg)
36 17-214
Howdoyoufixit?
publicclassPingPong{publicstaticsynchronizedvoidmain(String[]a){Threadt=newThread(()->pong());t.start();System.out.print("Ping");}privatestaticsynchronizedvoidpong(){System.out.print("Pong");}}
NowprintsPingPong
![Page 37: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/37.jpg)
37 17-214
Themoral
• InvokeThread.start,notThread.run• java.lang.ThreadshouldnothaveimplementedRunnable
![Page 38: Principles of Software Construction: Objects, …2019/11/05 · 17-214 2 Administrivia • Homework 5a due 9 a.m. tomorrow • Midterm exam available on Gradescope – Regrade requests](https://reader034.vdocuments.us/reader034/viewer/2022050418/5f8e57fa17d0f109144ed2f3/html5/thumbnails/38.jpg)
38 17-214
Summary
• Concurrentprogrammingcanbehardtogetright– Easytointroducebugseveninsimpleexamples
• Comingsoon:– Higher-levelabstractionsforconcurrency– Programstructureforconcurrency– Frameworksforconcurrentcomputation