Sharing Objects Ch. 3

Similar documents
CMSC 433 Programming Language Technologies and Paradigms. Sharing Objects

Advanced concurrent programming in Java Shared objects

Sharing Objects. Java and Android Concurrency.

Concurrency WS 2010/2011 The Java Memory Model

Get out, you will, of this bind If, your objects, you have confined

Lecture 17: Sharing Objects in Java

The Java Memory Model

Advanced MEIC. (Lesson #18)

G52CON: Concepts of Concurrency

Safety SPL/2010 SPL/20 1

The New Java Technology Memory Model

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

CMSC 433 Spring 2013 Exam 1

Design of Thread-Safe Classes

CMSC 433 Programming Language Technologies and Paradigms. Synchronization

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

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 5 Programming with Locks and Critical Sections

The Java Memory Model

3/25/14. Lecture 25: Concurrency. + Today. n Reading. n P&C Section 6. n Objectives. n Concurrency

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Memory system behavior: volatile variables. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 6. Volatile variables and concurrency

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

CSE332: Data Abstractions Lecture 23: Programming with Locks and Critical Sections. Tyler Robison Summer 2010

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

Synchronization SPL/2010 SPL/20 1

Audience. Revising the Java Thread/Memory Model. Java Thread Specification. Revising the Thread Spec. Proposed Changes. When s the JSR?

CSE332: Data Abstractions Lecture 19: Mutual Exclusion and Locking

Java Memory Model. Jian Cao. Department of Electrical and Computer Engineering Rice University. Sep 22, 2016

Introduction to Locks. Intrinsic Locks

CS 450 Exam 2 Mon. 11/7/2016

Programming Paradigms for Concurrency Lecture 3 Concurrent Objects

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

D Programming Language

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources

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

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

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

Unix System Programming - Chapter 2, part a

Threads and Java Memory Model

Races. Example. A race condi-on occurs when the computa-on result depends on scheduling (how threads are interleaved)

Threads Cannot Be Implemented As a Library

7/6/2015. Motivation & examples Threads, shared memory, & synchronization. Imperative programs

Motivation & examples Threads, shared memory, & synchronization

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

Lab. Lecture 26: Concurrency & Responsiveness. Assignment. Maze Program

CSE 374 Programming Concepts & Tools

RACE CONDITIONS AND SYNCHRONIZATION

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

Pre- and post- CS protocols. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 7. Other requirements for a mutual exclusion algorithm

SPIN, PETERSON AND BAKERY LOCKS

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

Concurrency: State Models & Design Patterns

CPSC 261 Midterm 2 Thursday March 17 th, 2016

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018

Concurrency. Glossary

Process Management And Synchronization

Thread Synchronization: Too Much Milk

Threads Questions Important Questions

Java Threads and intrinsic locks

Threads and Parallelism in Java

Multiple Inheritance. Computer object can be viewed as

Synchronization via Transactions

Introduction to OS Synchronization MOS 2.3

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

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming.

Last Class: Synchronization Problems!

Synchronization I. Jo, Heeseung

CSE 153 Design of Operating Systems

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

CSE 153 Design of Operating Systems

! Why is synchronization needed? ! Synchronization Language/Definitions: ! How are locks implemented? Maria Hybinette, UGA

Operating Systems (2INC0) 2017/18

Can Seqlocks Get Along with Programming Language Memory Models?

G52CON: Concepts of Concurrency

Program Graph. Lecture 25: Parallelism & Concurrency. Performance. What does it mean?

Synchronising Threads

Deadlock and Monitors. CS439: Principles of Computer Systems February 7, 2018

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

Models of concurrency & synchronization algorithms

Safety and liveness for critical sections

Parallel Programming: Background Information

Parallel Programming: Background Information

[module 2.2] MODELING CONCURRENT PROGRAM EXECUTION

CHAPTER 6: PROCESS SYNCHRONIZATION

CS 450 Exam 2 Mon. 4/11/2016

Thread Synchronization: Foundations. Properties. Safety properties. Edsger s perspective. Nothing bad happens

G52CON: Concepts of Concurrency

CMSC 132: Object-Oriented Programming II

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

Enforcing Mutual Exclusion Using Monitors

Review of last lecture. Peer Quiz. DPHPC Overview. Goals of this lecture. Lock-based queue

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Josh Bloch Charlie Garrod Darya Melicher

Java Platform Concurrency Gotchas

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Chapter 4: Writing Classes

Atomicity CS 2110 Fall 2017

Transcription:

Sharing Objects Ch. 3 Visibility What is the source of the issue? Volatile Dekker s algorithm Publication and Escape Thread Confinement Immutability Techniques of safe publication Assignment 1

Visibility To write correct shared-state concurrent programs we have to know when changes made in one thread become visible in other threads Our intuitions gained from sequential programming provide the wrong answers! 2

Sequential Consistency Language definition assures you that if you assign to a variable in one statement, the effect of that assignment will be visible in a later-executed statement x = 1; x = x+1; if (x==2) { But only if the statements are executed in the same thread! Think how awful programming would be if this were not the case! 3

Sequential consistency does not hold for concurrent threads An assignment may never become visible in a different thread Assignments done in some order in one thread may become visible in arbitrary order in a different thread and in different orders in different threads y = 0; x = 1; x = 3; y = 2; // if (y==2) { // can t assume that x==3 here Not even that x==1 x == 3 4

Why? Compiler writers and computer architects pursue speed in the usual case Keep variables in registers as much as possible Re-order stores to exploit memory architecture Re-order instructions, move them out of loops, etc. to improve performance These optimizations operate without knowledge of any concurrent activity (esp. the hardware ones). 5

Synchronization How do we fix this? Control of visibility is a second role for synchronization the first was to provide atomicity The same mechanisms that provide atomicity also fix the visibility problem Another synchronization mechanism called volatile fixes visibility but not atomicity stale data is possible unless synchronization is used for every access, read and write, to a variable 6

Out-of-thin-air safety Even if you don t use synchronization for shared variable accesses Java guarantees that what is read will be something that was written by your program (or automatically initialized) EXCEPTION: 64-bit longs and doubles NOTE: C/C++ do not make this guarantee even for sequential code (Your program will not see values that appear out of thin air) 7

Visibility Guarantee Provided by Intrinsic Locks A thread holding a lock is guaranteed to see all updates performed while any other thread previously held the same lock. Another reason for the rule: every shared variable should be protected by exactly one lock 8

volatile variables Any data member variable or static variable can be declared volatile volatile int x; Accesses to volatile variables require no locking and hence cannot block After writing a volatile variable x in thread A and reading it in thread B, thread B can see all writes visible to A at the time of its write, not just the write to x 9

Using a volatile variable instead of locks Writes to the variable do not depend on its previous value or the variable is only updated in one thread The variable is not related by an invariant to other shared variables Locking is not needed for any other reason (if locking is used, volatile is unnecessary) 10

Terminology and History A critical section is a general term for code sequence that must be executed atomically for correctness. Synchronized blocks implement critical sections Before hardware implementations had explicit synchronization instructions (test-and-set, e.g.) programmers had to protect critical sections using only normal memory reads and writes 11

Dekker s synchronization algorithm boolean enter1 = false; boolean enter2 = false; int turn = 1; { while(true) { /* Thread 1 */ enter1 = true; while (enter2) { if (turn==2) { enter1 = false; while (turn==2) yield(); enter1 = true; /* critical section */ enter1 = false; turn = 2; /* non-critical section */ /* Thread 2 */ { while(true) { enter2 = true; while (enter1) { if (turn==1) { enter2 = false; while (turn==1) yield(); enter2 = true; /* critical section */ enter2 = false; turn = 1; /* non-critical section */ 12

Discussion What has to be done to Dekker s algorithm in light of our previous discussion about visibility? Like other manually constructed synchronization techniques, Dekker s algorithm is intended to: 1. Provide mutual exclusion 2. Avoid deadlock 3. Avoid unnecessary delay if one thread wants in and the other doesn t the first is not delayed 4. Ensure eventual entry if a thread wants in it eventually gets in 13

Assignment Please, no handwritten work 1. After inserting the necessary volatile declarations, argue convincingly that Dekker s algorithm exhibits the four properties listed on slide 13. 2. Based on what you know so far, how well does Java s intrinsic synchronization meet these properties 3. Write sequential code that abuses the class UnsafeStates in Fig. 3.6. 4. Turn in on web site turnin page by Jan. 31. 14

Publication part 1: avoiding escape Publishing making an object available outside of its current scope Store it where other code can find it Return it from a non-private method Pass it to a method of another class Escape incorrect publication Publishing internal, private state (violates encapsulation) Publishing an object also publishes objects referenced by its non-private fields Publishing an object to a different thread, while it is being constructed, violates thread safety 15

Unsafe approach to listener registration Fig. 3.7 public class ThisEscape { public ThisEscape(EventSource source) { source.registerlistener( new EventListener() { public void onevent(event e) { dosomething(e); ); 16

SafeListener Fig. 3.8 public class SafeListener { private final EventListener listener; private SafeListener () { listener = new EventListener() { public void onevent(event e) { dosomething(e); ; public static SafeListener newinstance(eventsource source) { SafeListener safe = new SafeListener(); source.registerlistener(safe.listener); return safe; 17

2. Thread Confinement Recall that one approach to thread safety is to not share state between threads How can we do that: 1. Only ever put object reference on the stack (in local variables) relies on the property of Java that references to stack variables cannot be obtained. 2. Use the ThreadLocal class: it s getter and setter store values s.t. each thread has its own copy 18 3. Ad hoc thread confinement

3. Immutability How to do immutability properly is itself a bit tricky next time. 19

Publication Part 2: Safe publication Previously: how to avoid unwanted publication Now: how to safely publish when publication is desired 20