Charlie Garrod Michael Hilton

Similar documents
Charlie Garrod Bogdan Vasilescu

Josh Bloch Charlie Garrod Darya Melicher

Principles of Software Construction: Concurrency, Part 1

Josh Bloch Charlie Garrod Darya Melicher

Charlie Garrod Bogdan Vasilescu

Charlie Garrod Michael Hilton

Principles of Software Construction: Concurrency, Part 1

Principles of Software Construction: Concurrency, Part 2

Principles of Software Construction: Concurrency, Part 2

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Josh Bloch Charlie Garrod Darya Melicher

Charlie Garrod Bogdan Vasilescu

CMSC 132: Object-Oriented Programming II

Threads. COMP 401 Fall 2017 Lecture 22

Principles of So3ware Construc9on. A formal design process, part 2

A formal design process, part 2

Excep&ons and Threads

Threads Chate Patanothai

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

Threads and Java Memory Model

Charlie Garrod Michael Hilton

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 2 (Can't live with it, can't live without it.

Thread-unsafe code. Synchronized blocks

Lecture 24: Java Threads,Java synchronized statement

COMP 322: Fundamentals of Parallel Programming

Question Points Score Total 100

PRINCIPLES OF OPERATING SYSTEMS

Charlie Garrod Michael Hilton

i219 Software Design Methodology 11. Software model checking Kazuhiro Ogata (JAIST) Outline of lecture

Problems with Concurrency. February 19, 2014

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

Solu%on: locks. Every object has a lock associated with it. A lock can be owned by at most one thread.

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Threads and Parallelism in Java

THREADS AND CONCURRENCY

Principles of Software Construction: Objects, Design, and Concurrency. The Perils of Concurrency Can't live with it. Cant live without it.

Question Points Score Total 100

Charlie Garrod Michael Hilton

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 2 Can't live with it. Cant live without it.

Java s Implementation of Concurrency, and how to use it in our applications.

Java Puzzlers, Episode VI: The PhantomReference Menace. Attack of the Clone. Revenge of the Shift.

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Concurrency Quiz: Java Threads

CSCD 330 Network Programming

Introduction to Java Threads

Midterm #1. CMSC 433: Programming Language Technologies and Paradigms. October 14, 2013

THREADS & CONCURRENCY

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II)

Carnegie Mellon. Synchroniza+on : Introduc+on to Computer Systems Recita+on 14: November 25, Pra+k Shah (pcshah) Sec+on C

F. Tip and M. Weintraub CONCURRENCY

What you see is what you get?

CS11 Java. Fall Lecture 7

THREADS & CONCURRENCY

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 9.

Concurrency. Fundamentals of Computer Science

Michele Van Dyne MUS 204B Concurrency Issues

Lecture 29: Java s synchronized statement

CMSC 132: Object-Oriented Programming II. Threads in Java

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

CSCD 330 Network Programming

THE UNIVERSITY OF WESTERN AUSTRALIA SAMPLE EXAM QUESTIONS 2007 WITH SOLUTIONS SCHOOL OF COMPUTER SCIENCE CITS3213 CONCURRENT PROGRAMMING (PART II)

Synchronization in Java

CMSC 433 Programming Language Technologies and Paradigms. Synchronization

Synchronization. Announcements. Concurrent Programs. Race Conditions. Race Conditions 11/9/17. Purpose of this lecture. A8 released today, Due: 11/21

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

CSE 374 Programming Concepts & Tools

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Concurrency. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

Charlie Garrod Michael Hilton

Jonathan Aldrich Charlie Garrod

Multiple Inheritance. Computer object can be viewed as

Introduction to Threads

Java Threads. Introduction to Java Threads

CMSC 330: Organization of Programming Languages

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Reminder from last <me

Exercise Session Week 8

Threads, Concurrency, and Parallelism

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

Josh Bloch Charlie Garrod Darya Melicher

COMP 110/L Lecture 6. Kyle Dewey

CS 351 Design of Large Programs Threads and Concurrency

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

Principles of Software Construction: Objects, Design, and Concurrency. The Perils of Concurrency, Part 3 Can't live with it. Can't live without it.

Synchroniza+on II COMS W4118

+ Today. Lecture 26: Concurrency 3/31/14. n Reading. n Objectives. n Announcements. n P&C Section 7. n Race conditions.

Threads and Concurrency in Java

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

CSCI [4 6] 730 Operating Systems. Example Execution. Process [& Thread] Synchronization. Why does cooperation require synchronization?

Synchronization Lecture 23 Fall 2017

User Space Multithreading. Computer Science, University of Warwick

Outline of lecture. i219 Software Design Methodology 10. Multithreaded programming. Kazuhiro Ogata (JAIST)

Exercise Session Week 8

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Part IV Other Systems: I Java Threads

The Continuing Adventures of Java Puzzlers: Tiger Traps

Sec$on 6: Mutual Exclusion. Michelle Ku5el

Transcription:

Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 5: Concurrency Introduc9on to concurrency, part 2 Concurrency primi9ves, con9nued Charlie Garrod Michael Hilton School of Computer Science 1

Administrivia Homework 5a due 9 a.m. tomorrow Framework design discussion 2 nd midterm exam returned today Reading due today: Java Concurrency in Prac9ce, Sec9ons 11.3 and 11.4 2

A sudden reversal: one solu9on? public class ReversedList<T> extends AbstractList<T> { private final List<T> source; public ReversedList<T>(List<T> source) { this.source = source; @Override public int size() { return source.size(); @Override public T get(int index) { return source.get(size() index 1); public class Mysterious { public static <T> List<T> reverseof(list<t> source) { return new ReversedList<>(source); 3

A sudden reversal: a slightly beser solu9on class ReversedList<T> extends AbstractList<T> { private final List<T> source; ReversedList<T>(List<T> source) { this.source = source; @Override public int size() { return source.size(); @Override public T get(int index) { return source.get(size() index 1); public class Mysterious { public static <T> List<T> reverseof(list<t> source) { return new ReversedList<>(source); 4

A sudden reversal: a slightly even beser solu9on public class Mysterious { private class ReversedList<T> extends AbstractList<T> { private final List<T> source; public ReversedList<T>(List<T> source) { this.source = source; @Override public int size() { return source.size(); @Override public T get(int index) { return source.get(size() index 1); public static <T> List<T> reverseof(list<t> source) { return new ReversedList<>(source); 5

A sudden reversal: a beser solu9on public class Mysterious { public static <T> List<T> reverseof(list<t> source) { return new AbstractList<T>() { @Override public int size() { return source.size(); @Override public T get(int index) { return source.get(size() index 1); ; 6

Plane and simple design challenge 7

Puzzler: Racy LiSle Number 8

Puzzler: Racy LiSle Number import org.junit.test; import static org.junit.assert.assertequals; public class LittleTest { int number; @Test public void test() throws InterruptedException { number = 0; Thread t = new Thread(() -> { assertequals(2, number); ); number = 1; t.start(); number++; t.join(); 9

How o3en does this test pass? import org.junit.test; import static org.junit.assert.assertequals; public class LittleTest { int number; @Test public void test() throws InterruptedException { number = 0; Thread t = new Thread(() -> { assertequals(2, number); ); number = 1; t.start(); number++; t.join(); (a) It always fails (b) It some;mes passes (c) It always passes (d) It always hangs 10

How o3en does this test pass? (a) It always fails (b) It some9mes passes (c) It always passes but it tells us nothing (d) It always hangs JUnit doesn t see asser;on failures in other threads 11

Another look import org.junit.*; import static org.junit.assert.*; public class LittleTest { int number; @Test public void test() throws InterruptedException { number = 0; Thread t = new Thread(() -> { assertequals(2, number); // JUnit never sees the exception! ); number = 1; t.start(); number++; t.join(); 12

How do you fix it? (1) // Keep track of assertion failures during test volatile Exception exception; volatile Error error; // Triggers test case failure if any thread asserts failed @After public void teardown() throws Exception { if (error!= null) throw error; if (exception!= null) throw exception; 13

How do you fix it? (2) Thread t = new Thread(() -> { try { assertequals(2, number); catch(error e) { error = e; catch(exception e) { exception = e; ); Now it some;mes passes* *YMMV (It s a race condi9on) 14

The moral JUnit does not well-support concurrent tests You might get a false sense of security Concurrent clients beware 15

Puzzler: Ping Pong public class PingPong { public static synchronized void main(string[] a) { Thread t = new Thread( () -> pong() ); t.run(); System.out.print("Ping"); private static synchronized void pong() { System.out.print("Pong"); 16

What does it print? public class PingPong { public static synchronized void main(string[] a) { Thread t = new Thread( () -> pong() ); t.run(); System.out.print("Ping"); private static synchronized void pong() { System.out.print("Pong"); (a) PingPong (b) PongPing (c) It varies 17

What does it print? (a) PingPong (b) PongPing (c) It varies Not a mul;threaded program! 18

Another look public class PingPong { public static synchronized void main(string[] a) { Thread t = new Thread( () -> pong() ); t.run(); // An easy typo! System.out.print("Ping"); private static synchronized void pong() { System.out.print("Pong"); 19

How do you fix it? public class PingPong { public static synchronized void main(string[] a) { Thread t = new Thread( () -> pong() ); t.start(); System.out.print("Ping"); private static synchronized void pong() { System.out.print("Pong"); Now prints PingPong 20

The moral Invoke Thread.start, not Thread.run java.lang.thread should not have implemented Runnable 21

Key concepts from last Thursday 22

An easy fix: public class BankAccount { private long balance; public BankAccount(long balance) { this.balance = balance; static synchronized void transferfrom(bankaccount source, BankAccount dest, long amount) { source.balance -= amount; dest.balance += amount; public synchronized long balance() { return balance; 23

Concurrency control with Java's intrinsic locks synchronized (lock) { Synchronizes en9re block on object lock; cannot forget to unlock Intrinsic locks are exclusive: One thread at a 9me holds the lock Intrinsic locks are reentrant: A thread can repeatedly get same lock synchronized on an instance method Equivalent to synchronized (this) { for en9re method synchronized on a sta9c method in class Foo Equivalent to synchronized (Foo.class) { for en9re method 24

Some simple ac9ons are not atomic Increment is not atomic i++; is actually 1. Load data from variable i 2. Increment data by 1 3. Store data to variable i Also, Java Language Spec allows word-tearing on 64 bit values high bits low bits 25

Yet another example: coopera9ve thread termina9on public class StopThread { private static boolean stoprequested; public static void main(string[] args) throws Exception { Thread backgroundthread = new Thread(() -> { while (!stoprequested) /* Do something */ ; ); backgroundthread.start(); TimeUnit.SECONDS.sleep(42); stoprequested = true; 26

How do you fix it? public class StopThread { private static boolean stoprequested; private static synchronized void requeststop() { stoprequested = true; private static synchronized boolean stoprequested() { return stoprequested; public static void main(string[] args) throws Exception { Thread backgroundthread = new Thread(() -> { while (!stoprequested()) /* Do something */ ; ); backgroundthread.start(); TimeUnit.SECONDS.sleep(42); requeststop(); 27

A beser(?) solu9on public class StopThread { private static volatile boolean stoprequested; public static void main(string[] args) throws Exception { Thread backgroundthread = new Thread(() -> { while (!stoprequested) /* Do something */ ; ); backgroundthread.start(); TimeUnit.SECONDS.sleep(42); stoprequested = true; 28

Today: Concurrency, mo9va9on and primi9ves Midterm exam 2 recap Racy puzzlers More basic concurrency in Java Some challenges of concurrency Concurrency primi9ves for coordina9on S9ll coming soon: Higher-level abstrac9ons for concurrency Program structure for concurrency Frameworks for concurrent computa9on 29

A liveness problem: poor performance public class BankAccount { private long balance; public BankAccount(long balance) { this.balance = balance; static synchronized void transferfrom(bankaccount source, BankAccount dest, long amount) { source.balance -= amount; dest.balance += amount; public synchronized long balance() { return balance; 30

A liveness problem: poor performance public class BankAccount { private long balance; public BankAccount(long balance) { this.balance = balance; static void transferfrom(bankaccount source, BankAccount dest, long amount) { synchronized(bankaccount.class) { source.balance -= amount; dest.balance += amount; public synchronized long balance() { return balance; 31

A proposed fix?: lock spli1ng public class BankAccount { private long balance; public BankAccount(long balance) { this.balance = balance; static void transferfrom(bankaccount source, BankAccount dest, long amount) { synchronized(source) { synchronized(dest) { source.balance -= amount; dest.balance += amount; 32

A liveness problem: deadlock A possible interleaving of opera9ons: bugsthread locks the daffy account daffythread locks the bugs account bugsthread waits to lock the bugs account daffythread waits to lock the daffy account 33

A liveness problem: deadlock public class BankAccount { private long balance; public BankAccount(long balance) { this.balance = balance; static void transferfrom(bankaccount source, BankAccount dest, long amount) { synchronized(source) { synchronized(dest) { source.balance -= amount; dest.balance += amount; 34

Avoiding deadlock The waits-for graph represents dependencies between threads Each node in the graph represents a thread An edge T1->T2 represents that thread T1 is wai9ng for a lock T2 owns Deadlock has occurred iff the waits-for graph contains a cycle One way to avoid deadlock: locking protocols that avoid cycles a b d e c h i f g 35

Avoiding deadlock by ordering lock acquisi9on public class BankAccount { private long balance; private final long id = SerialNumber.generateSerialNumber(); public BankAccount(long balance) { this.balance = balance; static void transferfrom(bankaccount source, BankAccount dest, long amount) { BankAccount first = source.id < dest.id? source : dest; BankAccount second = first == source? dest : source; synchronized (first) { synchronized (second) { source.balance -= amount; dest.balance += amount; 36

A subtle problem: The lock object is exposed public class BankAccount { private long balance; private final long id = SerialNumber.generateSerialNumber(); public BankAccount(long balance) { this.balance = balance; static void transferfrom(bankaccount source, BankAccount dest, long amount) { BankAccount first = source.id < dest.id? source : dest; BankAccount second = first == source? dest : source; synchronized (first) { synchronized (second) { source.balance -= amount; dest.balance += amount; 37

An easy fix: Use a private lock public class BankAccount { private long balance; private final long id = SerialNumber.generateSerialNumber(); private final Object lock = new Object(); public BankAccount(long balance) { this.balance = balance; static void transferfrom(bankaccount source, BankAccount dest, long amount) { BankAccount first = source.id < dest.id? source : dest; BankAccount second = first == source? dest : source; synchronized (first.lock) { synchronized (second.lock) { source.balance -= amount; dest.balance += amount; 38

Concurrency and informa9on hiding Encapsulate an object's state: Easier to implement invariants Encapsulate synchroniza9on: Easier to implement synchroniza9on policy 39