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

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

Java Threads and intrinsic locks

Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency

Java theory and practice: Going atomic The new atomic classes are the hidden gems of java.util.concurrent

Threads and Locks, Part 2. CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014

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

Atomicity CS 2110 Fall 2017

G52CON: Concepts of Concurrency

CS 351 Design of Large Programs Threads and Concurrency

Synchronization Lecture 23 Fall 2017

Threads and Java Memory Model

COMP 322: Fundamentals of Parallel Programming

Introduction to Locks. Intrinsic Locks

Synchronization COMPSCI 386

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

Buffer & File Optimization. Cloud Databases DataLab CS, NTHU

Race Conditions & Synchronization

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

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

Parallel linked lists

Models of concurrency & synchronization algorithms

Synchronization SPL/2010 SPL/20 1

Learning from Bad Examples. CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Java Platform Concurrency Gotchas

Race Conditions & Synchronization

Results of prelim 2 on Piazza

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 2 Can't live with it. Cant live without it.

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 2 (Can't live with it, can't live without it.

CS11 Java. Fall Lecture 7

Atomic Variables & Nonblocking Synchronization

Synchronization Lecture 24 Fall 2018

Sharing Objects Ch. 3

Lecture 16: Thread Safety in Java

Dr.-Ing. Michael Eichberg

Design of Thread-Safe Classes

What's wrong with Semaphores?

-Aditya Bhave CSCI-5448 Graduate Presentation

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

Dr.-Ing. Michael Eichberg

Advanced concurrent programming in Java Shared objects

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

Concurrency API. Bram Inniger October 25, Based on previous work by Pavel Grigorenko and Rein Raudjärv

Java Monitor Objects: Synchronization (Part 1)

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

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

Last Class: Deadlocks. Today

Synchronization problems with semaphores

Today: Synchronization. Recap: Synchronization

Agenda. Highlight issues with multi threaded programming Introduce thread synchronization primitives Introduce thread safe collections

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

Java Semaphore (Part 1)

Spin Locks and Contention. Companion slides for The Art of Multiprocessor Programming by Maurice Herlihy & Nir Shavit

The New Java Technology Memory Model

Threads Synchronization

CSE 332: Locks and Deadlocks. Richard Anderson, Steve Seitz Winter 2014

CONCURRENT API AND PARALLEL PROGRAMMING

More Synchronization; Concurrency in Java. CS 475, Spring 2018 Concurrent & Distributed Systems

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data

What is a thread anyway?

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

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Data Races and Locks

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

Concurrent Programming Benoît Garbinato

Spin Locks and Contention. Companion slides for The Art of Multiprocessor Programming by Maurice Herlihy & Nir Shavit

Concurrency, Thread. Dongkun Shin, SKKU

Last Class: CPU Scheduling! Adjusting Priorities in MLFQ!

Synchronising Threads

THE UNIVERSITY OF WESTERN AUSTRALIA SAMPLE EXAM QUESTIONS 2007 WITH SOLUTIONS SCHOOL OF COMPUTER SCIENCE CITS3213 CONCURRENT PROGRAMMING (PART II)

Synchronized Methods of Old Versions of Java

Multi-Threaded Programming Design CSCI 201 Principles of Software Development

CS 159: Parallel Processing

Spin Locks and Contention. Companion slides for Chapter 7 The Art of Multiprocessor Programming by Maurice Herlihy & Nir Shavit

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Background. vanilladb.org

CSE 374 Programming Concepts & Tools

Lecture 9: Introduction to Monitors

Faculty of Computers & Information Computer Science Department

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

JAVA EXAMPLES - SOLVING DEADLOCK

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

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

Spin Locks and Contention

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

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

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

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Lecture 8: September 30

Shared Objects & Mutual Exclusion

Paradigmas de Computação Paralela

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem

Josh Bloch Charlie Garrod Darya Melicher

Core Java Syllabus. Pre-requisite / Target Audience: C language skills (Good to Have)

CSL373: Lecture 5 Deadlocks (no process runnable) + Scheduling (> 1 process runnable)

G52CON: Concepts of Concurrency

Processes and Threads. Industrial Programming. Processes and Threads (cont'd) Processes and Threads (cont'd)

Programmazione di sistemi multicore

Locks Chapter 4. Overview. Introduction Spin Locks. Queue locks. Roger Wattenhofer. Test-and-Set & Test-and-Test-and-Set Backoff lock

Transcription:

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

Today's lecture More on Java's mutual exclusion tools Intrinsic locks Developing our own thread-safe classes Concurrent collections 2

Synchronized methods public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; public synchronized void decrement() { c--; public synchronized int value() { return c; Given a particular instance of SynchronizedCounter, only 1 thread may be inside any synchronized method at a tme Any other threads wishing to call a synchronized method on the same instance must wait in turn Synchronized constructors don't make sense! Synchronized methods are rather coarse-grained, the entire method is serialised, even if some statements are not in a critical section (and could safely be executed concurrently by other threads) 3

Synchronized blocks public class SynchronizedCounter { private int c = 0; // Object intrinsiclock = new Object(); public void increment() { synchronized(this) { // start lock (using this object's intrinsic lock) c++; // end lock Similar to synchronized methods, but the synchronized regions are finer-grained now, allowing for more concurrency Every instance in Java has its own intrinsic lock When a synchronized method or synchronised(this) is called, that instance's intrinsic lock is used.. So by sharing the same lock, this still might be too coarse-grained for some situations 4

public class SynchronizedCounter { private int a = 0; private int b = 0; Object locka = new Object(); Object lockb = new Object(); public void inca() { synchronized(locka) { a++; public void incb() { synchronized(lockb) { b++; Synchronized blocks Provides better concurrency :-) But starts to complicate things :-( 5

Atomic variables public class AtomicCounter { private AtomicInteger c = new AtomicInteger(0); public void increment() { c.incrementandget(); public void decrement() { c.decrementandget(); public void set(int newvalue) { c.set(newvalue); public int value() { return c.get(); Have a look at the java.util.concurrent.atomic package Lots more methods inside AtomicInteger Lots more classes inside this package AtomicBoolean AtomicReference 6

Locks class LockedCounter { private final Lock lock = new ReentrantLock(); private int c = 0; public void increment() { lock.lock(); try { c++; finally { lock.unlock()... Have a look at the java.util.concurrent.locks package More flexibility and efficient than using synchronized blocks Optional fair policy trylock() getqueuelength()... 7

Deadlock! class UhOh { private final Lock locka = new ReentrantLock(); private final Lock lockb = new ReentrantLock(); private int a, b; public void doa() { locka.lock(); lockb.lock(); lockb.unlock(); locka.unlock(); public void dob() { lockb.lock(); locka.lock(); locka.unlock(); lockb.unlock();... 8

Concurrent collections By using the previous tools, you are able to produce thread-safe classes. This means that users of your class don't need to implement mutual exclusion on your class Good OOP practice! encapsulation! By extending this, classes that represent collections can also be thread-safe.. so multiple threads writing and reading into the collection safely! The collection itself is aware of all the threads and implements mutual exclusion whereever needed.. makes your life easier, you don't need to do any locking, etc! reassuring to make use of a well-tested class (code reuse!) See the java.util.concurrent package, lots of collections there 9

Concurrent collections Why can't we share an ArrayList between multiple threads? Recall the Counter example! What will be the size() of the collection after a couple of threads add something!?!?! That's why we can't share any mutable objects that are not thread-safe! Demo! A collection of Animals shared by multiple owners (i.e. multiple threads)! Iterator (not thread-safe) (e.g.) ArrayList (not thread-safe) Parallel Iterator (thread-safe) (e.g.) ConcurrentLinkedQueue, LinkedBlockingQueue, etc 10