Week 9 Building blocks.

Slides:



Advertisements
Similar presentations

Advertisements

50.003: Elements of Software Construction Week 6 Thread Safety and Synchronization.
Identity and Equality Based on material by Michael Ernst, University of Washington.
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Multithreaded Programs in Java. Tasks and Threads A task is an abstraction of a series of steps – Might be done in a separate thread – Java libraries.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Effective Java: Concurrency Last Updated: Fall 2011.
Lecture8 – Ch 5 Higher-level concurrency patterns Synchronized collections Concurrent collections Producer-consumer pattern  Serial thread confinement.
CSC Multiprocessor Programming, Spring, 2011 Outline for Chapter 5 – Building Blocks – Library Classes, Dr. Dale E. Parson, week 5.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Designing a thread-safe class  Store all states in public static fields  Verifying thread safety is hard  Modifications to the program hard  Design.
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 Wrapup CS221 – 4/29/09. Concurrent Collections Java supplies a set of concurrent collections you can use manage sets of data in a multi- threaded.
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)
Concurrency CS 510: Programming Languages David Walker.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L21 (Chapter 24) Multithreading.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Sharing Objects – Ch. 3 Visibility What is the source of the issue? Volatile Dekker’s algorithm Publication and Escape Thread Confinement Immutability.
02/17/2010CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Java 5 Threading CSE301 University of Sunderland Harry Erwin, PhD.
Discussion Week 3 TA: Kyle Dewey. Overview Concurrency overview Synchronization primitives Semaphores Locks Conditions Project #1.
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.
1 Concurrent Languages – Part 1 COMP 640 Programming Languages.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
In the name of Allah The Proxy Pattern Elham moazzen.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
Collections. The Plan ● Why use collections? ● What collections are available? ● How are the collections different? ● Examples ● Practice.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Java Threads 1 1 Threading and Concurrent Programming in Java Queues D.W. Denbo.
Multi-Threaded Programming Design CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Internet Software Development Controlling Threads Paul J Krause.
Practice Session 8 Blocking queues Producers-Consumers pattern Semaphore Futures and Callables Advanced Thread Synchronization Methods CountDownLatch Thread.
4061 Session 21 (4/3). Today Thread Synchronization –Condition Variables –Monitors –Read-Write Locks.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
Synchronizing threads, thread pools, etc.
Kernel Locking Techniques by Robert Love presented by Scott Price.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Sharing Objects  Synchronization  Atomicity  Specifying critical sections  Memory visibility  One thread’s modification seen by the other  Visibility.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 24 th, 2010 The University of Georgia.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Synchronizing Threads with Semaphores
SPL/2010 Synchronization 1. SPL/2010 Overview ● synchronization mechanisms in modern RTEs ● concurrency issues ● places where synchronization is needed.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
System Programming Practical Session 4: Concurrency / Safety.
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.
CSC Multiprocessor Programming, Spring, 2012 Chapter 10 – Avoiding Liveness Hazards Dr. Dale E. Parson, week 11.
Software Design 13.1 From controller to threads l Threads are lightweight processes (what’s a process?)  Threads are part of a single program, share state.
Java.util.concurrent package. concurrency utilities packages provide a powerful, extensible framework of high-performance threading utilities such as.
Monitor Pattern Read only Collection views Synchronized Collections views Concurrent HashMap The Vehicle Tracker Example.
Background on the need for Synchronization
CSC Multiprocessor Programming, Spring, 2011
Lecture 8 Thread Safety.
Synchronization Lecture 23 – Fall 2017.
Condition Variables and Producer/Consumer
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Condition Variables and Producer/Consumer
More on Thread Safety CSE451 Andrew Whitaker.
Race Conditions & Synchronization
Java Concurrency 17-Jan-19.
Java Concurrency.
Java Concurrency.
Java Concurrency 29-May-19.
“The Little Book on Semaphores” Allen B. Downey
CSC Multiprocessor Programming, Spring, 2011
Presentation transcript:

Week 9 Building blocks

Week 9: Outline Synchronized Collections Concurrent Collections Producer-Consumer Pattern Synchronizers

Synchronized Collections Some of the older (jdk2) collections are synchronized and thus thread-safe, but there are problems: with compound actions. Vector Hashtable Collections.synchronizedXxx

Example Why is this not ideal? public static void doSomething (Vector list) { synchronized (list) { for (int i = 0; i < list.size(); i++) { doSomething(list.get(i)); } Vector is considered a “legacy” collection class. “Modern” collection Classes use Iterator.

Example What could happen to the following code if widgetList is accessed by multiple threads? ***Internally, javac generates code that uses an Iterator, repeatedly calling hasNext and next to iterate the list. If a modification count (associated with the collection) changes during iteration, hasNext or next throws ConcurrentModificationException. This is called fail-fast. List<Widge> widgeList = Collections.synchronizedList(new ArrayList<Widget>()); … for (Widget w : widgetList) { doSomething(w); } Is it possible to ConcurrentModificationException with one thread only?

Hidden Iterator Lock everywhere a shared collection might be iterated. class HiddenIterator { private final Set<Integer> set = new HashSet<Integer>(); public synchronized void add(Integer i) { set.add(i); } public synchronized void remove (Integer i) { set.remove(i); } public void addTenThings() { Random r = new Random(); for (int i = 0; i < 10; i++) { add(r.nextInt()); } System.out.println ("DEBUG: added ten elements to " + set);

Discussion Problems with locking a collection Alternative? If the collection is large or the task performed is lengthy, other threads could wait a long time. It increases the risk of problems like deadlock. The longer a lock is held, the more likely it is to be contended. Alternative? Clone the collection, lock and iterate the copy. Week 13: How about designing concurrent collections without ever using locks?

Concurrent Collections Java 5.0 improves on the synchronized collection by providing several concurrent collection classes. Replacing synchronized collections with concurrent collections can offer dramatic scalability improvement with little risk.

ConcurrentHashMap It is a HashMap designed for concurrency. It uses a finer-grained locking mechanism called lock striping. Uses an array of 16 locks. Each lock guards 1/16 of the hash buckets. Bucket N is guarded by lock N mod 16. The iterators returned by ConcurrentHashMap are weakly consistent instead of fail-fast. It cannot be locked for exclusive access.

Cohort Exercise 1 Given WorkerThread.java which performs operations on a given Map, design an experiment to show the performance difference between Collections.synchronizedMap and ConcurrrentHashMap. Sample Program: HashMapExp.java

CopyOnWriteArrayList It is a concurrent replacement for a synchronized list that offers better concurrency in some common situations. A new copy of the collection is created and published (using volatile) every time it is modified. All write operations are protected by the same lock and read operations are not protected.  When is this probably not efficient?

BlockingQueue Producers and consumers are very common in programs; Usually some kind of buffering is involved between P and C; The buffer can be implemented as a blocking queue. Blocking queues are a powerful resource management tool for building reliable applications: they make your program more robust to overload by throttling activities that threaten to produce more work than can handled.

Cohort Exercise 2 Analyze the following class which implements the skeleton of Google Desktop, and fix potential problems with BlockingQueue. GDesktopProb.java

Synchronizers A synchronizer is any object that coordinates the control flow of threads based on its state. Semaphores Latches Barriers Mutexes

Barriers A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. The barrier is often called cyclic because it can be re-used after the waiting threads are released. Thread A Thread B Thread C Barrier Click here for a sample program: BarrierExample.java

Semaphores A semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. Thread A Thread B Thread C Semaphore (with 2 permits) Click here for a sample program: SemaphoreExample.java

Cohort Exercise 3 Use semaphore to implement a BoundedHashSet. The class skeleton is given in BoundedHashSetQ.java. Hint: you can initialize the semaphore to the desired maximum size of the set. Click here for a sample program: BoundedHashSet.java

CountDownLatch A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. Click here for a sample program: CountDownLatchExample.java

Cohort Exercise 4 Given an (large) array of strings (of grades), write a multi-threaded program, using CountDownLatch, to check whether the array contains 7 “F”. Stop all threads as soon as possible. Click here for a sample program: CountDownLatchExercise.java

More … Phaser (introduced in Java 7) A reusable synchronization barrier, similar in functionality to CyclicBarrier and CountDownLatch but supporting more flexible usage.

FutureTask Future task are made up of Future and Callable, the result bearing relative of Runnable. There are several ways to complete: Normal completion; cancellation; and exception. Once a FutureTask is completed in cannot be restarted. Future.get() returns the result immediately if ‘the future is here’ (Task is completed) and Blocks if the task is not complete yet. Sample program: FutureTaskExample.java

Example Nearly every server application uses some form of caching. Poor concurrency Click here for a sample program: Cache.java Is it good to have the cache in this case? Thread A: L service(a) U Thread B: L service(b) U L Return cache(a) U Thread C: Click here for a sample program: CacheV1.java

Example Minor problem service(a) not in cache compute service(a) add service(a) to cache Thread A service(a) not in cache compute service(a) add service(a) to cache Thread B This is a big problem if service(a) is required to execute once-and-only-once. Click here for a sample program: CacheV2.java

Example Minor problem service(a) not in cache put Future in Cache compute service(a) set result Thread A service(a) not in cache put Future in cache compute service(a) set result Thread B This is a big problem if service(a) is required to execute once-and-only-once.

Cohort Exercise 5 Fix the minor problem on the previous slide using ConcurrentMap.putIfAbsent(). Notice that you can’t apply client-side locking on ConcurrentMap. Click here for a sample program: CacheV3.java

Summary It is the mutable state, stupid. Make fields final unless they need to be mutable. Immutable objects are automatically thread-safe. Encapsulation makes managing complexity practical. Guard each mutable with a lock. Guard all participants of an invariant with the same lock. Hold locks for the duration of compound actions. Any program that accesses a mutable from multiple threads. without synchronization is a broken program. Never rely on clever reasoning on why you do not need. synchronization in those situations. Include thread safety into the design process or explicitly document that your class is (intentionally) not thread-safe. Document your synchronization policy.