Design of Thread-Safe Classes

Similar documents
Lecture 19: Composing Objects in Java

Sharing Objects Ch. 3

Advanced concurrent programming in Java Shared objects

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

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

Composing Objects. Java and Android Concurrency.

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

CS 520 Theory and Practice of Software Engineering Fall 2018

CS 520 Theory and Practice of Software Engineering Fall 2017

CS 520 Theory and Practice of Software Engineering Fall 2017

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

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

Synchronization SPL/2010 SPL/20 1

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

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

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

The Java Collections Framework. Chapters 7.5

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

Sharing Objects. Java and Android Concurrency.

Java HashMap Interview Questions

Lecture 4. The Java Collections Framework

Introduction to Locks. Intrinsic Locks

More thread safety and Concurrent collections. Nasser Giacaman CompSci 230: Software Design and Construction

Java Concurrency. Towards a better life By - -

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

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

Introduction to Programming Using Java (98-388)

Advanced MEIC. (Lesson #18)

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

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

The Java Memory Model

Effective Concurrent Java. Brian Goetz Sr. Staff Engineer, Sun Microsystems

CSE Lecture 19: Concurrency 11 Nov Nate Nystrom UTA

The New Java Technology Memory Model

Titanium. Titanium and Java Parallelism. Java: A Cleaner C++ Java Objects. Java Object Example. Immutable Classes in Titanium

Java Platform Concurrency Gotchas

Common Java Concurrency pitfalls. Presented by : Kunal Sinha Austin Java Users Group 03/26/2019

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Synchronization Lecture 23 Fall 2017

Race Conditions & Synchronization

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Do inner private classes maintain the thread-safety of the outer class

Topic 10: The Java Collections Framework (and Iterators)

Programmazione di sistemi multicore

Topics in Enterprise Information Management

Principles of Software Construction: Concurrency, Part 2

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

CMSC 433 Spring 2013 Exam 1

Programming Languages and Techniques (CIS120)

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

Top Down Design vs. Modularization

CMSC 433 Programming Language Technologies and Paradigms. Sharing Objects

CSE 332: Data Structures & Parallelism Lecture 18: Race Conditions & Deadlock. Ruth Anderson Autumn 2017

Java Threads. COMP 585 Noteset #2 1

Outline. iterator review iterator implementation the Java foreach statement testing

Fundamental language mechanisms

The Java Memory Model

Applied Unified Ownership. Capabilities for Sharing Across Threads

CIS 120 Midterm II November 16, 2012 SOLUTIONS

Lecture 17: Sharing Objects in Java

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

Threads and Java Memory Model

Race Conditions & Synchronization

Modular Reasoning about Aliasing using Permissions

Java Programming. Price $ (inc GST)

EXAMINATIONS 2012 END-OF-YEAR SWEN222. Software Design. Question Topic Marks 1. Design Quality Design Patterns Design by Contract 12

Object Oriented Programming and Design in Java. Session 19 Instructor: Bert Huang

Kotlin/Native concurrency model. nikolay

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

Basic Principles of analysis and testing software

Efficient Java (with Stratosphere) Arvid Heise, Large Scale Duplicate Detection

Thread-unsafe code. Synchronized blocks

MultiJav: A Distributed Shared Memory System Based on Multiple Java Virtual Machines. MultiJav: Introduction

CIS 120 Midterm II November 16, Name (printed): Pennkey (login id):

Synchronization Lecture 24 Fall 2018

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

Shared state model. April 3, / 29

For this section, we will implement a class with only non-static features, that represents a rectangle

Programming Languages and Techniques (CIS120)

Safety SPL/2010 SPL/20 1

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

System Programming. Practical Session 4: Threads and Concurrency / Safety

Actors in the Small. Making Actors more Useful. Bill La

G52CON: Concepts of Concurrency

Multi-threaded Performance And Scalability

Section 8: Design Patterns. Slides by Alex Mariakakis. with material from David Mailhot, Hal Perkins, Mike Ernst

Concurrent Programming using Threads

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

Monitors; Software Transactional Memory

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

Atomicity CS 2110 Fall 2017

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Java 8 Programming for OO Experienced Developers

Programming Paradigms for Concurrency Lecture 3 Concurrent Objects

CMSC 330: Organization of Programming Languages

Multithreading and Interactive Programs

Based on slides by Prof. Burton Ma

Transcription:

Design of Thread-Safe Classes 1

Topic Outline Thread-Safe Classes Principles Confinement Delegation Synchronization policy documentation 2

Thread-safe Class Design Process Identify the object s state (variables) Identify state invariants Establish policy for managing concurrent access to the object s state Give examples of three types of constraints to consider when identifying state invariants. You must understand an object s invariants during the design process to ensure thread safety. 3

Thread-safe: Post-conditions Post-conditions what transformation does a method perform? New start in terms of original state. Example: set_v1 postcondition is v2 and v3 unchanged. Related to but different from invariant defines legal state transitions. MORAL It is impossible to ensure thread safety without knowledge of the object's state invariant and its method post-conditions. Such constraints generate atomicity and encapsulation requirements. 4

Thread-safe: State Dependent Operations Post-conditions what transformation does a method perform? Pre-conditions under what conditions can a method be called? Example: Try to pop an element off an empty stack. In sequential system this is an error: Return null value. Raise an exception. With concurrency, may be a temporary condition - design choice. Handle with stack's lock + wait / notify. Potential problem: Tightly coupled to the intrinsic locking mechanism. With richer structures, can be difficult to get correct. Better solution: Use of library synchronizer classes (next chapter). 5

Thread-safe: State Ownership Class design element : data that object owns Owner of the object decides locking protocol Be aware if/when object gets published Be aware of object references within objects that escape Need to think about ownership models when passing objects: Are you transferring ownership? Making a short-term loan? Creating a joint-ownership? Split ownership. What is an example of the split ownership model. 6

Thread-safe Classes: State Start with the fields: All primitive that s it! Object references include those object s fields. State is whatever data determines object structural integrity public class Point { private float x, y ; public Point(float x, float y) { this.x = x ; this.y = y ; public float get_x() { public float get_y() { public float set_x(float nx) { public float set_y(float ny) { public class Triangle { private Point v1, v2, v3 ; public Triangle(Point v1, Point v2, Point v3) {...

Thread-safe Classes: Invariant Invariant = structural rules of the road. For a triangle, points cannot be collinear. Where can Triangle invariant be violated? public class Point { private float x, y ; public Point(float x, float y) { this.x = x ; this.y = y ; public float get_x() { public float get_y() { public float set_x(float nx) { public float set_y(float ny) { public class Triangle { private Point v1, v2, v3 ; public Triangle(Point v1, Point v2, Point v3) { if ( colinear(v1,v2,v3) ) throw new Error() ; this.v1 = v1 ; this.v2 = v2 ; this.v3 = v3 ; public void set_v1(point nv1) { if (colinear(nv1, v2, v3) ) throw new Error() ; v1 = nv1 ; public void set_v2(point nv2) { public void set_v3(point nv3) { public Point[] get_vertices( ) { private boolean colinear(point v1, Point v2, Point v3) {

Thread-safe Classes: Invariant Fix - make Points immutable Is this sufficient? public class Point { private final float x, y ; public Point(float x, float y) { this.x = x ; this.y = y ; public float get_x() { public float get_y() { public float set_x(float nx) { public float set_y(float ny) { public class Triangle { private Point v1, v2, v3 ; public Triangle(Point v1, Point v2, Point v3) { if ( colinear(v1,v2,v3) ) throw new Error() ; this.v1 = v1 ; this.v2 = v2 ; this.v3 = v3 ; public void set_v1(point nv1) { if (colinear(nv1, v2, v3) ) throw new Error() ; v1 = nv1 ; public void set_v2(point nv2) { public void set_v3(point nv3) { public Point[] get_vertices( ) { private boolean colinear(point v1, Point v2, Point v3) {

Thread-safe Classes: Concurrent Access Fix - make Points immutable Is this sufficient? public class Point { private final float x, y ; public Point(float x, float y) { this.x = x ; this.y = y ; public float get_x() { public float get_y() { public class Triangle { private Point v1, v2, v3 ; public Triangle(Point v1, Point v2, Point v3) { if ( colinear(v1,v2,v3) ) throw new Error() ; this.v1 = v1 ; this.v2 = v2 ; this.v3 = v3 ; public void synchronized set_v1(point nv1) { if (colinear(nv1, v2, v3) ) throw new Error() ; v1 = nv1 ; public void synchronized set_v2(point nv2) { public void synchronized set_v3(point nv3) { public Point[] synchronized get_vertices( ) { private boolean colinear(point v1, Point v2, Point v3) {

Topic Outline Design of Thread-Safe Classes Confinement Delegation Synchronization policy documentation

(Instance) Confinement Want to use thread unsafe objects in a thread safe way. Encapsulate in wrapper object. Encapsulation makes it easier to ensure proper lock held when manipulating the wrapped object. Proxy pattern example: Same interface - just controlled for concurrency Synchronized methods in proxy interface Explicit synchronization on unsafe object's lock Or wrapper could be abstraction built on unsafe class Thread safe course with enrollment based on unsafe HashSet. Thread safe queue based on unsafe ArrayList. Java "monitor" pattern. Note - can be the default lock or any other one used consistently. What design pattern is used & how might it support safe access? 12

Confinement Example - Implicit Lock public class Dictionary { private final HashMap<String, String> dict = new HashMap<String, String>() ; public synchronized String getdef(string word) { return dict.get(word) ; public synchronized void adddef(string word, String def) { if ( dict.get(word) == null ) { dict.put( word, def ) ; public synchronized Map<String, String> getmap() { return Collections.unmodifiableMap( dict ) ; What is being used as the lock in this example?

Confinement Example - Explicit Lock public class Dictionary { private final HashMap<String, String> dict = new HashMap<String, String>() ; private Object lock = new Object() ; public String getdef(string word) { synchronized(lock) { return dict.get(word) ; public synchronized void adddef(string word, String def) { synchronized(lock) { if ( dict.get(word) == null ) { dict.put( word, def ) ; Is there an advantage to using a explicit vs an implicit lock? public synchronized Map<String, String> getmap() { synchronized(lock) { return Collections.unmodifiableMap( dict ) ;

Topic Outline Design of Thread-Safe Classes Confinement Delegation Synchronization policy documentation

Delegation Using thread safe classes "under the hood." Can sometimes delegate safety to these classes. public class Dictionary { private final ConcurrentMap<String, String> dict = new ConcurrentHashMap<String, String>() ; private final Map<String, String> unmodifiable = Collections.unmodifiableMap( dict ) ; public String getdef(string word) { return dict.get(word) ; public void adddef(string word, String def) { dict.putifabsent( word, def ) ; public Map<String, String> getmap() { return unmodifiable ;

Delegation Failure public class Range{ // Invariant: min <= max // AtomicInteger provides for thread-safe min & max objects private final AtomicInteger min = new AtomicInteger(0) ; private final AtomicInteger max = new AtomicInteger(0) ; public void setmin(int m) { if ( m > max.get() ) throw new Error("min " + m + " > max") ; min.set(m) ; public void setmax(int m) { if ( m > max.get() ) throw new Error("max " + m + " < min") ; max.set(m) ; public boolean inrange(int i) { return i >= min.get() && i <= max.get() ; Is Range thread-safe? Why or why not?

Topic Outline Design of Thread-Safe Classes Confinement Delegation Synchronization policy documentation

Synchronization Policy Documentation Clients need to know thread safety guarantees if any. Maintainers / extenders need to know synchronization policy. Use of immutable objects. Use of volatile variables. Use of synchronized to create thread safe objects. Use of delegation to create thread safe objects. Useful information not found in the code What invariant interdependencies exist (e.g., iteration) How interdependencies are guarded. What each lock controls (scope).

Looking ahead We have covered approaches to concurrent design that primarily use traditional Java mechanisms to deal with mutable state. Three options for addressing state in design: 1. Shared Mutability 2. Isolated Mutability 3. Immutability Design with immutability requires more effort since it requires a different design approach than we may be used to. But, the tradeoff is LESS need for low level synchronization mechanisms on our part and fewer concurrency headaches. 20