Lecture 7 First mid-term: Feb 23 Assignment on Construction, Publishing and Visibility is posted (and we will discuss momentarily)

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Ken Birman 1. Refresher: Dekers Algorithm Assumes two threads, numbered 0 and 1 CSEnter(int i) { int J = i^1; inside[i] = true; turn = J; while(inside[J]
– R 7 :: 1 – 0024 Spring 2010 Parallel Programming 0024 Recitation Week 7 Spring Semester 2010.
50.003: Elements of Software Construction Week 6 Thread Safety and Synchronization.
Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Effective Java: Concurrency Last Updated: Fall 2011.
/ PSWLAB Concurrent Bug Patterns and How to Test Them by Eitan Farchi, Yarden Nir, Shmuel Ur published in the proceedings of IPDPS’03 (PADTAD2003)
Monitors Chapter 7. The semaphore is a low-level primitive because it is unstructured. If we were to build a large system using semaphores alone, the.
Concurrency and Thread Yoshi. Two Ways to Create Thread Extending class Thread – Actually, we need to override the run method in class Thread Implementing.
Threading Part 4 CS221 – 4/27/09. The Final Date: 5/7 Time: 6pm Duration: 1hr 50mins Location: EPS 103 Bring: 1 sheet of paper, filled both sides with.
Threading Part 3 CS221 – 4/24/09. Teacher Survey Fill out the survey in next week’s lab You will be asked to assess: – The Course – The Teacher – The.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
Assignment – no class Wednesday All: watch the Google Techtalk “Getting C++ Threads Right” by Hans Boehm at the following link in place of Wednesday’s.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
Feb. 23, 2004CS WPI1 CS 509 Design of Software Systems Lecture #5 Monday, Feb. 23, 2004.
1 Sharing Objects – Ch. 3 Visibility What is the source of the issue? Volatile Dekker’s algorithm Publication and Escape Thread Confinement Immutability.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Week 9 Building blocks.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Java Programming: Advanced Topics
!!! Global Variables!!! are EVIL SSimply because you just write a school boy/gal?
50.003: Elements of Software Construction Week 8 Composing Thread-safe Objects.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Composition (Part 2) 1. Class Invariants  class invariant  some property of the state of the object that is established by a constructor and maintained.
1 Chapter years of CS and SE devoted to issues of composability: how to create solutions to big problems by combining (composing) solutions to smaller.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
Refactoring1 Improving the structure of existing code.
Internet Software Development Controlling Threads Paul J Krause.
Threading Eriq Muhammad Adams J
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Synchronizing threads, thread pools, etc.
Sharing Objects  Synchronization  Atomicity  Specifying critical sections  Memory visibility  One thread’s modification seen by the other  Visibility.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Java Thread and Memory Model
SPL/2010 Synchronization 1. SPL/2010 Overview ● synchronization mechanisms in modern RTEs ● concurrency issues ● places where synchronization is needed.
COMPSCI 230 S2C 2015 Software Design and Construction Synchronization (cont.) Lecture 4 of Theme C.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
SPL/2010 Guarded Methods and Waiting 1. SPL/2010 Reminder! ● Concurrency problem: asynchronous modifications to object states lead to failure of thread.
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
ANU COMP2110 Software Design in 2003 Lecture 10Slide 1 COMP2110 Software Design in 2004 Lecture 12 Documenting Detailed Design How to write down detailed.
13/03/07Week 21 CENG334 Introduction to Operating Systems Erol Sahin Dept of Computer Eng. Middle East Technical University Ankara, TURKEY URL:
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
CP — Concurrent Programming 6. Liveness and Guarded Methods Prof. O. Nierstrasz Wintersemester 2005 / 2006.
Refactoring1 Improving the structure of existing code.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
System Programming Practical Session 4: Concurrency / Safety.
CSC Multiprocessor Programming, Spring, 2012 Outline for Chapter 4 – Composing Objects – thread-safe object-oriented composition, Dr. Dale E. Parson,
Monitor Pattern Read only Collection views Synchronized Collections views Concurrent HashMap The Vehicle Tracker Example.
Sun Proprietary/Confidential: Internal Use Only 1 Multi-Threading Primer Byron Nevins December 10, 2007.
Java Thread Programming
Race Conditions & Synchronization
Healing Data Races On-The-Fly
Synchronization Lecture 23 – Fall 2017.
More on Thread Safety CSE451 Andrew Whitaker.
Race Conditions & Synchronization
Improving the structure of existing code
Java Concurrency 17-Jan-19.
Lecture 9 Synchronization.
Java Concurrency.
Java Concurrency.
Synchronization Lecture 24 – Fall 2018.
Software Design Lecture : 39.
Java Concurrency 29-May-19.
Software Engineering and Architecture
Synchronization Lecture 24 – Fall 2018.
Presentation transcript:

Lecture 7 First mid-term: Feb 23 Assignment on Construction, Publishing and Visibility is posted (and we will discuss momentarily)

Concurrency in C++ Discussion?

Construction, Visibility, and Publication Inspect real code for problems MARS MIPS simulator system Example

class SimThread extends SwingWorker { private MIPSprogram p; private int pc, maxSteps; private int[] breakPoints; private boolean done; private ProcessingException pe; private volatile boolean stop = false; private volatile AbstractAction stopper; private AbstractAction starter; private int constructReturnReason; At line 259 – in a SimThread this.pe = new ProcessingException(el); this.constructReturnReason = EXCEPTION; this.done = true; And at line 122 – in process that creates the SimThread ProcessingException pe = simulatorThread.pe; boolean done = simulatorThread.done; Also, note the comments and code at lines What’s wrong with this?

Advice Some uses in this code are suspicious but you can’t really tell whether they are wrong without looking at other modules. For things that catch your eye as suspicious write down your suspicions and the questions they raise about other modules. It’s a lot of code. What language constructs do you need to focus on?  When doing the homework, notice what makes it hard to determine whether the code is right or wrong  Learn from example code – both good and bad

Two common problems Composing a thread-safe class from unsafe building blocks Composing a thread-safe class when the building blocks are already thread-safe

Confinement Technique (4.2) – thread- safe object built from unsafe objects Allow access to a thread-unsafe object only through another object that is thread-safe public class PersonSet { private final Set mySet = new HashSet (); public synchronized void add(Person p) { mySet.add(p); } public synchronized boolean contains(Person p) { return myset.contains(p); } } hashSet is not ThreadSafe, PersonSet is Idea of ownership: PersonSet owns mySet but probably not the Persons contained in it

Monitors (4.2.1) (aside) Idea: a syntactic construct that pairs lock acquisition and release around a block of code  synchronized(foo) { … }  compared to explicit lock acquisition and release, encourages structured programs and avoids bugs due to failure to release locks Along with a mechanism for releasing a lock, suspending, and reacquiring the lock  wait() And a mechanism to wake up suspended threads  notify(), notifyAll() Monitors were independently invented by Sir Anthony Hoare and Per Brinch-Hansen in the mid-1970’s.

Danger in Confinement Technique Inadvertant publication of what is supposed to be private (confined) mutable state public synchronized MutablePoint getLocation(String id) { MutablePoint loc = locations.get(id); return loc == null ? Null : new MutablePoint(loc); } Public synchronized setLocation(String id, int x, int y) { MutablePoint loc = locations.get(id); if (loc == null) { … exception …} loc.x = x; loc.y = y } My preference would be to express this interface using ImmutablePoints.

Thread-safe objects built from thread-safe components – Delegating safety (4.3) Delegation: giving responsibility for thread safety to the object(s) containing this object’s state  ConcurrentMap (TS) instead of Map (not TS)  Atomic If this object’s state involves multiple other objects delegation may or may not work  If the sub-objects are independent, ok  If the sub-objects are related, this object must provide its own synchronization – even if all the sub-objects are themselves thread-safe

Example class PongPaddle { private final AtomicInteger left = new AtomicInteger(0); private final AtomicInteger right = new AtomicInteger(1); public void move(int dx) { left.getAndAdd(dx); right.getAndAdd(dx); } public void changeWidth(int dw) { right.getAndAdd(dw); } public boolean hit(int pos) { return left.get()<=pos && pos <= right.get(); } No visibility concerns What is the invariant that relates left and right? What should we do to fix it?

Reduce, Reuse, Recycle I am very anti cut-and-paste coding  Hard on the reader  Hard on the maintainer  Instead of 1 change, n changes  Instead of 1 bug, n bugs Design code so there only needs to be one copy (use parameterization, polymorphic parameterization) Even better, reuse existing code that does almost the right thing How does this interact with synchronization?

Adding functionality (4.4) Example: add putIfAbsent to a collection that already supports atomic contains() and add() methods Four approaches  Modify existing class  Extend existing class or  Wrap existing class – “client-side” locking  Composition - Add to existing class  Best way but  Assumes you have control over the existing class

Extend the existing class public class BetterVector extends Vector { public synchronized boolean putIfAbsent(E x) { boolean absent = !contains(x); if (absent) { add(x); } return absent; } Note the benefit of re-entrant locks! Note the implicit assumption that we understand the way that Vector does synchronization – using intrinsic locks, in this case Note that we don’t have any dependency on Vector’s implementation Vector is thread-safe Vector provides enough primitive building blocks to allow construction of putIfAbsent

Client-side locking Assume v is a thread-safe list obtained from Collections.synchronizedList(new ArrayList ()); Type of this object is List -- not extendable Any code that wants to do putIfAbsent item x to such a list, v, can write synchronized (v) { if (!v.contains(x)) v.add(x); } Could be placed in a helper class – beware you have to synchronize on the list and not on the helper object Now spreading the synchronization far and wide Still depending on knowing the synch policy for the wrapped object

Composition Mimic the idea of Collections.synchronizedList  Provide all the synchronization in a new object that extends the functionality of an existing object instance (not class)  Delegates most operations to the existing object Public class ImprovedList implements List { private final List list; public ImprovedList(List list) { this.list = list; } public synchronized boolean putIfAbsent(T x) … public synchronized boolean contains(T x) { return list.contains(x); } …

Intro to Chapter 5 – Building Blocks Chapter 4 was about low-level techniques This chapter is about libraries – embodiments of the techniques Section 5.1 Synchronized collections – read to see why you want to use Concurrent collections instead (we will not cover)  The idioms described are even more unsafe than asserted in the book because of visibility problems

Chapter 5 topics Concurrent collections (5.2) The ubiquitous producer-consumer pattern (5.3) Interruptable methods (5.4) Primitive synchronizers (5.5)