50.003: Elements of Software Construction Week 6 Thread Safety and Synchronization.

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.
– R 7 :: 1 – 0024 Spring 2010 Parallel Programming 0024 Recitation Week 7 Spring Semester 2010.
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Concurrent Programming Abstraction & Java Threads
Ch 7 B.
Ch. 7 Process Synchronization (1/2) I Background F Producer - Consumer process :  Compiler, Assembler, Loader, · · · · · · F Bounded buffer.
Chapter 6: Process Synchronization
Background Concurrent access to shared data can lead to inconsistencies Maintaining data consistency among cooperating processes is critical What is wrong.
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Concurrency 101 Shared state. Part 1: General Concepts 2.
1 CSC321 §2 Concurrent Programming Abstraction & Java Threads Section 2 Concurrent Programming Abstraction & Java Threads.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
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.
Race Conditions CS550 Operating Systems. Review So far, we have discussed Processes and Threads and talked about multithreading and MPI processes by example.
A. Frank - P. Weisberg Operating Systems Introduction to Cooperating Processes.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
CS510 Concurrent Systems Introduction to Concurrency.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
CSE 219 Computer Science III Multithreaded Issues.
50.003: Elements of Software Construction Week 8 Composing Thread-safe Objects.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
Internet Software Development Controlling Threads Paul J Krause.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Java Thread and Memory Model
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
Multiprocessor Cache Consistency (or, what does volatile mean?) Andrew Whitaker CSE451.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
13/03/07Week 21 CENG334 Introduction to Operating Systems Erol Sahin Dept of Computer Eng. Middle East Technical University Ankara, TURKEY URL:
CS533 – Spring Jeanie M. Schwenk Experiences and Processes and Monitors with Mesa What is Mesa? “Mesa is a strongly typed, block structured programming.
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
CSCI1600: Embedded and Real Time Software Lecture 17: Concurrent Programming Steven Reiss, Fall 2015.
CS510 Concurrent Systems Jonathan Walpole. Introduction to Concurrency.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Java Thread Programming
Multithreading / Concurrency
Multi Threading.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Synchronization Lecture 23 – Fall 2017.
COP 4600 Operating Systems Spring 2011
Multithreading.
COT 5611 Operating Systems Design Principles Spring 2014
Race Conditions & Synchronization
Threading And Parallel Programming Constructs
Threads and Memory Models Hal Perkins Autumn 2009
Multithreading.
Java Concurrency 17-Jan-19.
CSCI1600: Embedded and Real Time Software
Computer Science 2 06A-Java Multithreading
CSE 451: Operating Systems Autumn 2003 Lecture 7 Synchronization
CSE 451: Operating Systems Autumn 2005 Lecture 7 Synchronization
Java Concurrency.
CSE 153 Design of Operating Systems Winter 19
CS333 Intro to Operating Systems
Java Concurrency.
CSCI1600: Embedded and Real Time Software
Java Concurrency 29-May-19.
Problems with Locks Andrew Whitaker CSE451.
Don Porter Portions courtesy Emmett Witchel
CSE 542: Operating Systems
Presentation transcript:

50.003: Elements of Software Construction Week 6 Thread Safety and Synchronization

Plan for the Week What are thread safety? – data races – correctness How to ensure atomicity – Atomic variables – Race conditions check-then-act and lazy initialization – Locking Intrinsic locks and reentrancy How to ensure objects are shared correctly

Example Write a program such that N threads concurrently increment a static variable (initially 0) by 1. Set N to be 100, 1000, and see what is the value of the variable after all threads are done. FirstBlood.java

Is This Real? 0 1 Thread1 0 1 Thread2 count count = 0 count = 1 count = 2  This is assuming that count++ is one step. Or is it?

Reality is Messy Java Programs Bytecode JVM Physical Machine What are the atomic steps? What are the order of execution? What and where are the variable values?

What Really Happened? Thread1 read value of Count and assign it to a register Increment the register Write the register value back to Count Thread2 read value of Count and assign it to a register Increment the register Write the register value back to Count For double type, even read/write is not atomic!

What Really Happened? Thread1 r1 i1 w Thread2 r2 i2 w r2 i2 w2 r1 i1 w1 r1 i1 w1 r2 i2 w2

What Really Happened? Thread1 r1 i1 w Thread2 r2 i2 w r2 i2 w1 r1 i1 w2 count=1 Is this correct?

Specification What is correct depends on what we want – class invariants – pre-condition/post-condition – assertions Do document the specification! See a sample class: Stack.java

What Really Happened? Thread1 r1 i1 w Thread2 r2 i2 w2 Post-condition: count’ = count r2 i2 w2 r1 i1 w1 r1 i1 w1 r2 i2 w2

No Sharing = No Race Condition

Constants => No Race Condition

How to Ensure Atomicity Weapon 1: – Package java.util.concurrent.atomic – Example: AtomicInteger x = new AtomicInteger(0) x.incrementAndGet() //increments x by 1 atomically Operation A and B are atomic with respect to each other if, from the perspective of a thread executing A, when another thread executes B, either all of B has executed or none of it has. An atomic operation is one that is atomic with respect to all operations, including itself, that operate on the same state.

Cohort Exercise 1 (5 min) Fix the program you developed in Cohort Exercise 1 using AtomicInteger, assuming the post-condition is that the sum is the number of additions. FirstFixWithAtomicInteger.java

Compound Actions //withdraw from a bank account //check and update if (amount >= 1000) { amount = amount ; } SecondBlood.java

Intrinsic Locks Every Java object can implicitly act as a lock for purposes of synchronization. synchronized (lock) { //Access shared state guarded by lock } Intrinsic locks acts as mutexes (mutual exclusion locks), i.e., at most one thread may own the lock. Since only one thread at a time can execute a block of code guarded by a given lock, the synchronized blocks guarded by the same lock execute atomically with respect to one another.

How Lock Works Thread1 SecondBloodFixed.java 0 acquire lock release lock r1 i1 w1 Thread2 0 acquire lock release lock r2 i2 w2

Cohort Exercise 2 (10 min) Assuming that the correctness requirement is that “saving + cash = 5000” is an invariant, fix the following class: LockStaticVariables.java. Hint: Think about what is the lock? LockStaticVariablesFixed.java

Thread Safety If an object of type A is to be shared by multiple threads, A must be thread safe. “A class is thread-safe if no set of operations performs sequentially or concurrently on instances of a thread-safe class can cause an instance to be in an invalid state***.” Java Concurrency in Practice, Chapter 2 Stateless objects are always thread-safe *** whether a state is valid or not is defined by the specification

Guarding States with Locks Update related state variables in a single atomic operation For each mutable variable that may be accessed by more than one thread, all assesses to that variable must be performed with the same lock held. Every shared, mutable variable should be guarded by exactly one lock. Make it clear to maintainers which lock that is. For every invariant that involves more than one variable, all the variables involved in that invariant must be guarded by the same lock. ThirdBlood.java

Cohort Exercise 3 (15 min) CachedFactorizer.java provides a service to factorize integers. For efficiency, it stores the last input and its factors so that in case the new input is the same as the last (a.k.a. a hit), the saved factors are returned. It also counts the number of hits and maintains a hit ratio. Fix the class so that it becomes thread-safe. CachedFactorizerThreadSafe.java

Safety and Efficiency Why not declare every method synchronized? – Probably not efficient. Example, CachedFactorizer.java – Do not guarantee thread-safety. Example, if (!vector.contains(element)) { vector.add(element) } LserviceU L U L U Thread A Thread B Thread C More on performance later

Cohort Exercise 4 (10 min) Continue cohort exercise 4 so as to narrowing the scope of the synchronized block, without compromising thread-safety. CachedFactorizerThreadSafe.java

Lock-Ordering Deadlock public class LeftRightDeadlock { private final Object left = new Object (); private final Object right = new Object (); public void leftRight () { synchronized (left) { synchronized (right) { doSomething(); } public void rightLeft () { synchronized (right) { synchronized (left) { doSomethingElse(); } Thread A Thread B lock left lock right try to lock right wait for lock left wait forever More on deadlock later

Reentrancy When a thread requests a lock that is already held by another thread, the requesting thread blocks. Is this a problem? public class widget { public synchronized void doSomething () { … } public class LoggingWidget extends Widget { public synchronized void doSomething () { System.out.println (toString() + “: calling doSomething”); super.doSomething(); }

WAIT AND NOTIFY Week 6

Thread Control MethodRemarks start()Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. Thread.yield()A hint to the scheduler that the current thread is willing to yield its current use of a processor. Thread.sleep(long millis)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. wait()Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. notify()Wakes up a single thread that is waiting on this object's monitor. notifyAll()Wakes up all threads that are waiting on this object's monitor. join() Waits for this thread to die. interrupt() Interrupts this thread.

wait() Busy waiting is not efficient – Consider a voting system with two threads. One collects votes and the other is waiting to count the votes when the voting is completed. while (true) { synchronized(this) { if (votingComplete) { break; } Use wait()/nofityAll() to avoid busy waiting Voting.java

Cohort Exercise 5 (15 min) Producer/Consumer Pattern Exercise: fixed the Buffer class in BufferExample.hava so that it is thread-safe and efficient Producer Thread 1 Producer Thread 2 … Consumer Thread 1 Consumer Thread 2 … BoundedBuffer addItem removeItem BufferFixed.java

SYNCHRONIZATION Week 6

Example Initially A, B, r1 and r2 are all 0. What are the values of the variables after both threads complete? Is it possible to have B = 1 and r2 = 2 and A = 2 and r1 = 1? Thread 1Thread 2 1: r2 = A;3: r1 = B; 2: B = 1;4: A = 2;

Reality is Messy Java Programs Bytecode JVM Physical Machine What are the atomic steps? What are the order of execution? What and where are the variable values?

What are the order of execution? Java compiler might switch the order of sequential statements (e.g., for efficiency) Example: line 2 and line 3 might be switched 1.x++; 2.y++; 3.x++; How could we know the order of execution? Self-read: Java Memory Model

Where are the variables stored? FactorThread.java; NoVisibility.java new ready old ready How could we know where?

Remedy Visibility guarantees for synchronization Always use the proper synchronization whenever data is shared across threads. unlock M lock M thread A ……………… ……………… Everything before unlock on M … … is visible to everything after the lock on M

Example public class MutableInteger { private int value; public int get() { return value; } public void set(int value) { this.value = value;} } public class MutableInteger { private int value; public synchronized int get() { return value; } public synchronized void set(int value) { this.value = value;} } What is the problem here?

Locking and Visibility Locking is not just about mutual exclusion; it is also about memory visibility. To ensure that all threads see the most up-to-date values of shared mutable variables, the reading and writing threads must synchronize on a common lock.

Volatile Variables An update to a volatile variable is propagated predictably to other threads. Locking can guarantee both visibility and atomicity; volatile variables can only guarantee visibility. private static volatile boolean ready; … while (!ready) { Thread.yield(); } …

Cohort Exercise 6 (5 min) Fix Experiment.java with volatile. ExperimentFixed.java

Summary We have so far learned how to write basic multi-threaded program and how to guarantee thread-safety for simple classes.