Principles of Software Construction: Concurrency, Part 2

Similar documents
Principles of Software Construction: Concurrency, Part 2

Principles of Software Construction: Concurrency, Part 1

CS11 Java. Fall Lecture 7

Java Threads. Introduction to Java Threads

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

Java Threads. COMP 585 Noteset #2 1

Multiple Inheritance. Computer object can be viewed as

Threads and Parallelism in Java

Josh Bloch Charlie Garrod Darya Melicher

Threads and Java Memory Model

Principles of Software Construction: Concurrency, Part 1

Synchronization II: EventBarrier, Monitor, and a Semaphore. COMPSCI210 Recitation 4th Mar 2013 Vamsi Thummala

Charlie Garrod Michael Hilton

Info 408 Distributed Applications Programming Exercise sheet nb. 4

Introduction to Java Threads

G52CON: Concepts of Concurrency

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

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

Lecture 29: Java s synchronized statement

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

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

Threads Chate Patanothai

Concurrent Programming using Threads

Problems with Concurrency. February 19, 2014

Only one thread can own a specific monitor

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

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

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Charlie Garrod Bogdan Vasilescu

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

THREADS AND CONCURRENCY

Java 8 From Smile To Tears: Emotional Stampedlock

Models of concurrency & synchronization algorithms

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment.

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Concurrent Programming

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

7. MULTITHREDED PROGRAMMING

Threads, Concurrency, and Parallelism

CS 351 Design of Large Programs Threads and Concurrency

More Synchronization; Concurrency in Java. CS 475, Spring 2018 Concurrent & Distributed Systems

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem

Performance Throughput Utilization of system resources

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

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

From Smile To Tears: Emotional StampedLock

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data

CMSC 433 Programming Language Technologies and Paradigms Fall Locks & Conditions

Programming in Parallel COMP755

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

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

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

CMSC 132: Object-Oriented Programming II

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

CS 556 Distributed Systems

Synchronized Methods of Old Versions of Java

The Java Memory Model

Synchronization in Java

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Writing Parallel Programs COMP360

CST242 Concurrency Page 1

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

CS193k, Stanford Handout #8. Threads 3

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

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency

Advanced Concepts of Programming

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

CS 361 Concurrent programming Drexel University Spring 2000 Lecture 14. The dining philosophers problem

Java Threads. Written by John Bell for CS 342, Spring 2018

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Concurrency in Java Prof. Stephen A. Edwards

F. Tip and M. Weintraub CONCURRENCY

What is a thread anyway?

THREADS & CONCURRENCY

COMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization

Multithreaded Programming

Part IV Other Systems: I Java Threads

Programming Language Concepts: Lecture 11

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Chapter 32 Multithreading and Parallel Programming

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Parallel Programming Practice

Readers/Writers Problem. Readers/Writers: Scenario 1. Readers/Writers Problem. Today: Synchronization for Readers/Writers Problem

Communication & Synchronization. Lecture 3: Synchronization & Communication - Part 1. Shared variables. Communication Using Shared Memory

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

The New Java Technology Memory Model

Concurrent Programming Benoît Garbinato

CS370 Operating Systems

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

Parallel Programming Practice

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

CMSC 330: Organization of Programming Languages

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Definition: A thread is a single sequential flow of control within a program.

Transcription:

Principles of Software Construction: Concurrency, Part 2 Josh Bloch Charlie Garrod School of Computer Science 1

Administrivia Homework 5a due now Homework 5 framework goals: Functionally correct Well documented and easy to understand Interesting 2nd midterm exam returned today, after class 2

Key concepts from Tuesday Runnable interface represents work to be done To create a thread: new Thread(Runnable) To start thread: thread.start(); To wait for thread to finish: thread.join(); One sychronized static method runs at a time volatile communication sans mutual exclusion Must synchronize access to shared mutable state Else program will suffer safety and liveness failures 3

Outline I. Discrete Event Simulation exam question II. Wait/Notify - primitives for cooperation III. The dangers of over-synchronization 4

DES specification summary Simulator steps through executing events Time usually represented as an integer Events can do these things: Change the simulated system state Create and schedule new events to occur in future Cancel a future event, given a reference to event Stop the simulation Framework is sequential no concurrency Events scheduled for same time can run in any order 5

Minimal API for event and simulator 6

Event implementation 7

Simulator implementation (1) 8

Simulator implementation (2) 9

Zombie invasion spec summary Initial population: humans = 10 6, zombies = 4 On first day, each zombie goes hunting When a zombie hunts, one of these things happen p =.2, zombie infects human: zombies++, humans-- p =.2, zombie is destroyed: zombies-- p =.6, nothing happens (populations unchanged) If zombie survives, sleeps 1-10 days & hunts again Newly-infected zombie hunts day after infected Run till humans gone, zombies gone, or 100 years 10

Zombie invasion (1) 11

Zombie invasion (2) 12

Key design decisions No class to represent state explicitly State is merely the variables shared by events Eliminates need for generics Occam s Razor / When in doubt, leave it out Events have a Runnable, not a run method Enables use of anonymous class or lambda Favor composition over inheritance [EJ Item 16] Pending events represented as PriorityQueue Nice code and good performance 13

Outline I. Discrete Event Simulation exam question II. Wait/Notify - primitives for cooperation III. The dangers of over-synchronization 14

The basic idea is simple State (fields) protected by lock (synchronized) Sometimes, thread can t proceed till state is right So it waits with wait Automatically drops lock while waiting Thread that makes state right wakes waiting thread(s) with notify Waking thread must hold lock when it calls notify Waiting thread automatically gets lock when woken 15

But the devil is in the details Never invoke wait outside a loop! Loop tests condition before and after waiting Test before skips wait if condition already holds Necessary to ensure liveness Without it, thread can wait forever! Testing after waiting ensure safety Condition may not be true when thread wakens If thread proceeds with action, it can destroy invariants! 16

All of your waits should look like this synchronized (obj) { while (<condition does not hold>) { obj.wait();... // Perform action appropriate to condition 17

Why can a thread wake from a wait when condition does not hold? Another thread can slip in between notify & wake Another thread can invoke notify accidentally or maliciously when condition does not hold This is a flaw in java locking design! Can work around flaw by using private lock object Notifier can be liberal in waking threads Using notifyall is good practice, but causes this Waiting thread can wake up without a notify(!) Known as a spurious wakeup 18

Example: read-write locks (API) Also known as shared/exclusive mode locks private final RwLock lock = new RwLock(); lock.readlock(); try { // Do stuff that requires read (shared) lock finally { lock.unlock(); lock.writelock(); try { // Do stuff that requires write (exclusive) lock finally { lock.unlock(); 19

Example: read-write locks (Impl. 1) public class RwLock { // State fields are protected by RwLock's intrinsic lock /** Num threads holding lock for read. */ private int numreaders; /** Whether lock is held for write. */ private boolean writelocked; public synchronized void readlock() throws InterruptedException { while (writelocked) { wait(); numreaders++; 20

Example: read-write locks (Impl. 2) public synchronized void writelock() throws InterruptedException { while (numreaders!= 0 writelocked) { wait(); writelocked = true; public synchronized void unlock() { if (numreaders > 0) { numreaders--; else if (writelocked) { writelocked = false; else { throw new IllegalStateException("Lock not held"); notifyall(); // Wake any waiters 21

Caveat: RwLock is just a toy! It has poor fairness properties Readers can starve writers! java.util.concurrent provides an industrial strength ReadWriteLock More generally, avoid wait/notify In the early days it was all you had Nowadays, higher level concurrency utils are better 22

Outline I. Discrete Event Simulation exam question II. Wait/Notify - primitives for cooperation III. The dangers of over-synchronization 23

Broken Work Queue (1) public class WorkQueue { private final Queue<Runnable> queue = new ArrayDeque<>(); private boolean stopped = false; public WorkQueue() { new Thread(() -> { while (true) { // Main loop synchronized (queue) { // Locking on private obj. try { while (queue.isempty() &&!stopped) queue.wait(); catch (InterruptedException e) { return; if (stopped) return; // Causes thread to end queue.remove().run(); // BROKEN - LOCK HELD! ).start(); 24

Broken Work Queue (2) Broken Work Queue (2) public final void enqueue(runnable workitem) { synchronized (queue) { queue.add(workitem); queue.notify(); public final void stop() { synchronized (queue) { stopped = true; queue.notify(); 25

Perverse use of that shows flaw public static void main(string[] args) { WorkQueue wq = new WorkQueue(); // Enqueue task that starts thread that enqueues task... wq.enqueue(() -> { Thread t = new Thread(() -> { wq.enqueue(() -> { System.out.println("Hi Mom!"); ); ); ); //...and waits for thread to finish t.start(); try { t.join(); catch (InterruptedException e) { throw new AssertionError(e); 26

Luckily, it s easy to fix the deadlock public WorkQueue() { new Thread(() -> { while (true) { // Main loop Runnable task = null; synchronized (queue) { try { while (queue.isempty() &&!stopped) queue.wait(); catch (InterruptedException e) { return; if (stopped) return; // Causes thread to terminate task = queue.remove(); task.run(); // Fixed! "Open call" (no lock held) ).start(); 27

Never do callbacks while holding lock It is over-synchronization We saw it deadlock And it can do worse! If the callback goes back into the module holding the lock, it will not block, and can damage invariants! So always drop any locks before callbacks You may have to copy the callbacks under lock 28

Summary Discrete Event/Zombie problem was long & hard But sol n could be short & sweet with good design choices Never use wait outside of a while loop! Think twice before using it at all Neither an under- nor an over-synchronizer be Under-synchronization causes safety (& liveness) failures Over-synchronization causes liveness (& safety) failures 29