Monitor Pattern Read only Collection views Synchronized Collections views Concurrent HashMap The Vehicle Tracker Example.

Slides:



Advertisements
Similar presentations
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Advertisements

Concurrency 101 Shared state. Part 1: General Concepts 2.
Week 9, Class 3: Model-View-Controller Final Project Worth 2 labs Happens-Before ( SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors:
CS 11 java track: lecture 7 This week: Web tutorial:
IBM Software Group © 2004 IBM Corporation Compilation Technology Java Synchronization : Not as bad as it used to be! Mark Stoodley J9 JIT Compiler Team.
Concurrency and Thread Yoshi. Two Ways to Create Thread Extending class Thread – Actually, we need to override the run method in class Thread Implementing.
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 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.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
Principle 1 If more than one thread accesses a given state variable and one of them might write to it then All accesses to the variable must be correctly.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Proxy Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
Week 9 Building blocks.
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.
Data structures and algorithms in the collection framework 1 Part 2.
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.
In the name of Allah The Proxy Pattern Elham moazzen.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
Sharing Objects  Synchronization  Atomicity  Specifying critical sections  Memory visibility  One thread’s modification seen by the other  Visibility.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Consider the program fragment below left. Assume that the program containing this fragment executes t1() and t2() on separate threads running on separate.
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.
Thread basics. A computer process Every time a program is executed a process is created It is managed via a data structure that keeps all things memory.
System Programming Practical Session 4: Concurrency / Safety.
Optimistic Design CDP 1. Guarded Methods Do something based on the fact that one or more objects have particular states Make a set of purchases assuming.
Week 9, Class 3: Java’s Happens-Before Memory Model (Slides used and skipped in class) SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors:
Today Quiz not yet graded Final report requirements posted More on Multithreading Happens-Before in Java SE-2811 Slide design: Dr. Mark L. Hornick Content:
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
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.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Threads. Parsing fasta sequences in parallel Threads in GUIs.
Sun Proprietary/Confidential: Internal Use Only 1 Multi-Threading Primer Byron Nevins December 10, 2007.
Tutorial 2: Homework 1 and Project 1
EECE 310: Software Engineering
Chapter 19 Java Data Structures
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Faster Data Structures in Transactional Memory using Three Paths
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
Atomicity CS 2110 – Fall 2017.
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
CMPE212 – Stuff… Exercises 4, 5 and 6 are all fair game now.
Java Collections Overview
Dr. David Matuszek Heapsort Dr. David Matuszek
Overview of Memory Layout in C++
CSE 1030: Data Structure Mark Shtern.
Java Programming Arrays
More on Thread Safety CSE451 Andrew Whitaker.
Race Conditions & Synchronization
Producer-Consumer Problem
Printed on Monday, December 31, 2018 at 2:03 PM.
Java Concurrency 17-Jan-19.
Multicore programming
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
Concurrency and Immutability
Lecture 9 Synchronization.
Slide design: Dr. Mark L. Hornick
Java Concurrency.
Java Concurrency.
Java Concurrency 29-May-19.
Problems with Locks Andrew Whitaker CSE451.
CMPE212 – Reminders Assignment 2 due next Friday.
slides created by Ethan Apter
CO 303 Algorithm Analysis and Design
More concurrency issues
Threads and concurrency / Safety
Presentation transcript:

Monitor Pattern Read only Collection views Synchronized Collections views Concurrent HashMap The Vehicle Tracker Example

Why the frowny face?

Java monitor pattern – guard all state with “this”

Using a private lock guarantees that you control all access… (this is an alternative to the monitor pattern)

Monitor Pattern Read only Collection views Synchronized Collections views Concurrent HashMap The Vehicle Tracker Example

We extend AbstractSequence Our static initializer to set up our cached alphabet We’ve seen the “read only” view of an underlying collection is useful.. Immutability is a key tool in thread safety…

This is the “decorator” pattern. We wrap the collection is functions that throw an Exception if the underlying class is modified… UnmodifiableCollection Get() underlyingCollection Set() thows Exception()

Will print out 1 and then 2

Read only Collection views Synchronized Collections views Concurrent Collections The Vehicle Tracker Example

Alternatively (or in addition) we can create a synchronized collection. Only one thread at a time can use this collection… synchronizedCollection Get() underlyingCollection Set() synchronized(this)

Vector is a synchronized list using the monitor pattern (Vector is an equivalent to Collections.synchronizedList( myList ) )

Why the so-so face?

This is thread safe, but might not be what the user expects. Thread safe: the underlying data will not be corrupted! But may throw an Exception that the user isn’t expecting!

One solution (utilizing the monitor pattern). Make getting the last element atomic (so that what is the “last” element can’t be changed by different threads…)

You have to be careful when iterating… This will throw if the vector changes between calling.size() and calling.get() Again, this is threadsafe (the underlying data won’t get corrupted) But the user may get an exception they are not expecting The monitor pattern offers a solution (but could be very slow if the vector Is big and/or doSomething is slow; no concurrency while the lock is held!)

You have to be careful when iterating… This is equivalent to a for loop that calls.size (even though it doesn’t look like it!)

Why the frowny face?

Same problem. set.toString() iterates the set

Here is an attempt to add “put if absent” to a synchronized list What’s wrong here? Botched attempt to use the monitor pattern..

Here is an attempt to add “put if absent” to a synchronized list Botched attempt to use the monitor pattern.. The wrong object is locked!! These lock “list” This locks ListHelper

Every access to the returned list needs to respect the monitor pattern and call synchronized(list)

Why does this one work?

Composition (hasA) as an alternative to inheritance (isA)

We follow Bloch here, “favor composition over inheritance…”

Read only Collection views Synchronized Collections views Concurrent Collections The Vehicle Tracker Example

ConcurrentHashMap is a thread-safe HashMap

size() and isEmpty() are only approximate on concurrent collections Concurrent collections do not lock on this. If you grab a lock on the ConcurrentHashMap, that doesn’t stop another thread from writing at the same time, because these classes do not use the monitor pattern

Concurrent collections do not throw ConcurrentModification Exceptions Every time you run this, you will get a different answer… The state of the iterator is not rigorously defined, but it won’t throw an Exception Iteration gives you a view of the map at some point in time which may change

Many useful thread-safe functions are provided for you…

Putting lots of data into the Synchronized HashMap (still pretty fast…..) block until countDown() is called NUM_THREADS time

Significantly faster “for free” The concurrent hash map

The CopyOnWriteArrayList – concurrency not so much for free

CopyOnWriteArrayList Internal array #1 Thread A calls “add” Internal array #2 is created Thread B calls get and gets an element from array #1 CopyOnWriteArrayList Internal array #1 Internal array #2 Garbage collected Thread C calls get and gets an element from array #2 Thread safety through copying data…. Copy of internal arrays # is started Time

Read only Collection views Synchronized Collections views Concurrent Collections The Vehicle Tracker Example

The “Vehicle tracking” example

Solution #1: Thread safety through copying. Define a mutable point…

Thread safety via deep copies. Once the constructor has fired, no other thread can impact locations. User can think they are changing the underlying data, but calls to change mutablePoint don’t make changes any other user can see Assumes location doesn’t change during object construction!

Solution #2: Make points immutable – achieve thread safety through delegation

This will give a “real-time” view. Updates written by thread A are seen by Thread B Assumes points doesn’t change during object construction! Delegate thread safety to the ConcurrentHashMap Use the decorator pattern twice!