50.003: Elements of Software Construction Week 8 Composing Thread-safe Objects.

Slides:



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

Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 24 th, 2010 The University of Georgia.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
Designing a thread-safe class  Store all states in public static fields  Verifying thread safety is hard  Modifications to the program hard  Design.
Effective Java Gruppe Gul Items vi vil uddybe: # 15Minimize Mutability # 23 Don’t use raw types in new code # 47Know and use Libraries # 63Include failure-capture.
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.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
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.
1 Where did the synchronized methods go? Yes, there still exists the synchronized keyword. public synchronized void foo() {} public void foo(){ aLock.lock();
16-Jun-15 Java Threads Fine grained, shared state.
Lecture 7 First mid-term: Feb 23 Assignment on Construction, Publishing and Visibility is posted (and we will discuss momentarily)
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.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
Proxy Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
Week 9 Building blocks.
Ranga Rodrigo. Class is central to object oriented programming.
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
!!! Global Variables!!! are EVIL SSimply because you just write a school boy/gal?
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
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.
SPL/2010 Safety 1. SPL/2010 system designing for concurrent execution environments ● system: collection of objects and their interactions ● system properties:
Chapter 9 Object-Oriented Software Development F Software Development Process F Analyze Relationships Among Objects F Class Development F Class Design.
Optimistic Design 1. Guarded Methods Do something based on the fact that one or more objects have particular states  Make a set of purchases assuming.
Internet Software Development Controlling Threads Paul J Krause.
 A Collection class is a data type that is capable of holding a group of items.  In Java, Collection classes can be implemented as a class, along with.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
Sharing Objects  Synchronization  Atomicity  Specifying critical sections  Memory visibility  One thread’s modification seen by the other  Visibility.
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.
CS1101 Group1 Discussion 7 Lek Hsiang Hui comp.nus.edu.sg
System Programming Practical Session 4: Concurrency / Safety.
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
CP — Concurrent Programming 6. Liveness and Guarded Methods Prof. O. Nierstrasz Wintersemester 2005 / 2006.
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Confinement.
Singleton Pattern Presented By:- Navaneet Kumar ise
The Singleton Pattern (Creational)
System Programming Practical Session 4: Concurrency / Safety.
The const Keyword Extreme Encapsulation. Humble Beginnings There are often cases in coding where it is helpful to use a const variable in a method or.
CSC Multiprocessor Programming, Spring, 2012 Outline for Chapter 4 – Composing Objects – thread-safe object-oriented composition, Dr. Dale E. Parson,
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.
COMPOSITE PATTERN NOTES. The Composite pattern l Intent Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients.
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Monitor Pattern Read only Collection views Synchronized Collections views Concurrent HashMap The Vehicle Tracker Example.
Healing Data Races On-The-Fly
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
Synchronization Lecture 23 – Fall 2017.
More on Thread Safety CSE451 Andrew Whitaker.
Java Concurrency 17-Jan-19.
Simple Classes in Java CSCI 392 Classes – Part 1.
Java Concurrency.
Java Concurrency.
Java Concurrency 29-May-19.
Threads and concurrency / Safety
Presentation transcript:

50.003: Elements of Software Construction Week 8 Composing Thread-safe Objects

Objects which are accessed concurrently must be thread-safe. How do we systematically build complicated thread-safe data structures?

Plan of the Week Designing a thread-safe class Instance confinement Delegating thread safety Adding functionality to thread-safe classes Documenting synchronization policies

Design a Thread-Safe Class The design process for a thread-safe class should include these three basic elements: Identify the variables that form the object’s state; Identify the requirements (e.g., invariants, post-conditions) that constrain the state variables; Establish a policy for managing concurrent access to the objects state.

Step 1: Identifying States An object’s state includes all of its mutable variables – If they are all of primitive type, the fields comprise the entire state. – If the object has fields that are references to other objects, its state will encompass fields from those as well. Click here for a sample program: MyStack.java

Tips The smaller this state space, the easier it is to reason about. – Use “final” as long as you can. public class MyStack { private final int maxSize; private long[] stackArray; private int top; … }

Step 2: Identifying Requirements You cannot ensure thread safety without understanding an object’s specification. Constraints on the valid values or state transitions for state variables can create atomicity and encapsulation requirements. Click here for a sample program: MyStack.java

Step 3: Establishing Policy Guard each mutable state variable with one lock. Make it clear which lock. Add waiting (and notify) to handle pre- conditions. Click here for a sample program: MyStackThreadSafe.java

Cohort Exercise 1 (5 min) Similarly identify the pre-condition/post- condition of other methods in MyStack.java and make the class thread-safe.

The above method works based on the assumption that the only way to access the state in the class is through calls of visible methods.

INSTANCE CONFINEMENT Composing Thread-safe Objects

Encapsulating Data What is the problem? public class MyStack { private final int maxSize; private long[] stackArray; public int top; //top = -1 … }

Encapsulating Data Identify the intended scope of objects – To a class instance (e.g., a private data field) – To a lexical scope (e.g., a local variable) – To a thread (e.g., an object which is not supposed to be shared across threads) Instance confinement is one of the easiest ways to build thread-safe classes Click here for a sample program: PersonSet.java

Encapsulating Data Make sure the objects don’t escape their scope Bad Example 1: public class MyStack { private final int maxSize; public long[] stackArray; private int top; //top = -1 … }

Encapsulating Data Make sure the objects don’t escape their scope Bad Example 2: public class MyClass { private String[] states = new String[]{…}; private int size = states.length; public String[] getStates() { return states; }

Cohort Exercise 2 (20 min) Assume a taxi tracking system which tracks taxis in Singapore. The updater threads would modify taxi locations and the view thread would fetch the locations of the taxis and display them. Examine Tracker.java (shared by the updater thread and the view thread) and make it thread-safe. Hint: make copy of a data structure to ensure instance confinement. Click here for a sample program: TrackerFixed.java

DELEGATING THREAD SAFETY Patterns for Composing Thread-safe objects

Delegating Thread Safety Building thread-safe classes from thread-safe classes Example (from Week 6): public class FirstFixWithAtomicInteger { public static AtomicInteger count = new AtomicInteger(0); … } This works because the state of the class is count!

Cohort Exercise 3 (10 min) Continue cohort exercise 2. Examine the modified class DelegatingTracker.java and discuss whether it is thread safe or not. Click here for a sample program: DelegatingTracker.java

Publishing State Variables When is it safe to publish state variables? – If a state variable is thread-safe, does not participate in any invariant that constrain its value, and has no prohibited state transitions for any of its operations, then it can be safely published. – It still might not be a good idea, since publishing mutable variables constrains future development and opportunities for sub-classing.

Example: PublishingTracker.java Assuming that there is no additional constraints on vehicle locations, other than that they must be this given pair. PublishingTracker delegates its thread-safety to ConcurrentHashMap and Point.

Delegating Thread Safety If a class is composed to multiple independent thread-safe state variables, then it can delegate thread safety to the underlying state variables. If a class has invariants the relate its state variables, then delegation may not work.

Cohort Exercise 4 (10 min) Modify Range.java so that it is thread-safe. Click here for a sample program: RangeSafe.java

ADDING FUNCTIONALITY TO THREAD-SAFE CLASSES Composing Thread-safe Objects

Motivation How to extend a thread-safe class with new operations? – Method 1: modifying the class – Method 2: extending the class – Method 3: client-side locking – Method 4: composition

Modifying the Class If you have the source code, apply the knowledge that you acquired previously to add the required method in the class. Click here for a sample program: MyList.java

Extending the Class Sometimes a thread-safe class (e.g., a class from java.util.concurrent) supports almost all the operations we want. – Which lock is it using? Example 2: if you don’t have the source code, Click here for a sample program: BetterVector.java

Private Lock Instead of guarding state variables by locking “this”, private locks can be used too. Example: public class PrivateLock { private final Object myLock = new Object(); Widget widget; void someMethod() { synchronized(myLock) { //Access or modify the state of widget } Private Locks are flexible and risky.

Extending the class More fragile than adding code directly to a class, because the implementation of the synchronization policy is now distributed over multiple, separately maintained source files. Click here for a sample program: ExtendedPair.java and ExtendedPairWrong.java

Client-side Locking Example: Add a method addIfAbsent to Collections.synchronizedList – We don’t have the source code or enough access to the internal state so that we can extend the class. Client-side locking entails guarding client code that uses some object X with the lock X uses to guard its own state. public class ListHelper { public java.util.List list = Collections.synchronizedList(new ArrayList ()); }

Question Is this thread safe? public class ListHelper { public java.util.List list = Collections.synchronizedList(new ArrayList ()); public synchronized boolean putIfAbsent(E x) { boolean absent = !list.contains(x); if (absent) { list.add(x); } return absent; } Click here for a sample program: ListHelper.java

Example public static Object getLast(Vector list) { int lastIndex = list.size() - 1; return list.get(lastIndex); } public static void deleteLast(Vector list) { int lastIndex = list.size() - 1; list.remove(lastIndex); } size:10 Thread A Thread B size:10remove(9) get(9)

Cohort Exercise 5 (10 min) Assume that multiple threads may call the static methods defined in FirstExample.java, fix FirstExample for potential problems. Hint: In Javadoc, it is documented that the synchronized collections commits to a synchronization policy that supports client-side lockingJavadoc

Client-Side Locking Even more fragile than extending the class because it distributes the locking code for a class into classes that are totally unrelated to the class. – Modifying the class: keeps the locking code in the same class – Extending the class: distributes the locking code in the class hierarchy

Composition It is less fragile if list is accessed only through improvedList. It doesn’t care whether list is thread-safe or not. It adds performance penalty due to the extra layer of synchronization. Click here for a sample program: ImprovedList.java

Cohort Exercise 6 (15 min) Write a thread-safe class named SafeStack which extends java.util.Stack with two operations pushIfNotFull(E e) and popIfNotEmpty(). Do it in different ways and design an experiment to compare the performance of the two. Click here for a sample program: SafeStack.java

DOCUMENTING SYNCHRONIZATION POLICIES Patterns for Composing Thread-safe objects

Documenting Documentation is one of the most powerful tools for managing thread safety. – Document a class’s thread safety guarantees for its clients; document its synchronization policy for its maintainers. Is thread-safety documented in JDK?

One Case Tomcat Bug: – ugzilla/show_bug.cgi?id= ugzilla/show_bug.cgi?id= The fix Any problem?