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

Size: px
Start display at page:

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

Transcription

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

2 Agenda (Old) Synchronised Collections Concurrent Collections Synchronisers

3 Thread Safety A piece of code is thread-safe if it manipulates shared data structures only in a manner that guarantees safe execution by multiple threads at the same time.

4 (Old) Synchronised Collections

5 Java 1.0 java.util.vector java.util.hashtable Internally synchronised, and sync is not optional

6 Java 1.2 java.util.arraylist java.util.linkedlist java.util.hashmap java.util.treemap Not thread safe, must synchronise externally

7 java.util.collections Use synchronised polymorphic wrappers: Collections.sychronized[List Map Set ] (Conditionally) Thread safe

8 Compound Actions (1) 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);

9 Compound Actions (2) Interleaving of getlast() and deletelast() throws ArrayIndexOutOfBoundsException

10 Compound Actions: Client-side Locking public static Object getlast(vector list) { synchronized (list) { int lastindex = list.size() - 1; return list.get(lastindex); public static void deletelast(vector list) { synchronized (list) { int lastindex = list.size() - 1; list.remove(lastindex);

11 Iteration: Naively for (int i = 0; i < vector.size(); i++) { dosomething(vector.get(i)); This may throw ArrayIndexOutOfBoundsException

12 Iteration: Client-side Locking synchronized (vector) { for (int i = 0; i < vector.size(); i++) { dosomething(vector.get(i));

13 Iteration that may throw ConcurrentModificationException Iterator it = vector.iterator(); while (it.hasnext()) { dosomething(it.next()); Iterators returned by the synchronised collections are Fail-fast.

14 Beware of hidden Iterators Is this safe? for (Widget w : widgetlist) { dosomething(w); Or maybe this? System.out.println("Widgets: " + widgetlist);

15 Synchronise iterations Iteration requires explicit synchronisation: Set s = Collections.syn Set(new HashSet()); synchronized(s) { for (Iterator i = s.iterator(); i.hasnext(); ) { dosomething(i.next()); Use-case: Event Listeners Inefficient > make a copy!

16 Copy On Read (1) for (Iterator it = new ArrayList(vector).iterator(); it.hasnext(); ) { dosomething(it.next()); The constructor may throw ArrayIndexOutOfBoundsException or ConcurrentModificationException.

17 Copy On Read (2) for (Iterator it = Arrays.asList(vector.toArray()).iterator(); it.hasnext(); ) { dosomething(it.next()); Finally: Thread safe! (please don t use it though)

18 Performance The synchronised collections: Serialised access > not efficient Only one thread at once (thread contention) Reads, writes, iterations all use a single lock

19 Concurrent Collections

20 JSR166: Concurrency Utilities Chaired by prof. Doug Lea (State University of New York at Oswego) index.html

21 Concurrent Collections (Java 5) java.util.concurrent package: ConcurrentHashMap CopyOnWriteArrayList CopyOnWriteArraySet Designed for multiple threads More efficient Replaces synchronised HashMap, ArrayList and LinkedHashSet

22 ConcurrentHashMap Finer-grained locking mechanism: lock striping Multiple write locks, arbitrary many reads

23 Additional Atomic Map Operations interface ConcurrentMap<K,V> extends Map<K,V> { V putifabsent(k key, V value); boolean remove(k key, V value); boolean replace(k key, V oldval, V newval); V replace(k key, V newvalue); No need for client side locking!

24 putifabsent(key, value) if (map.containskey(key)) { return map.get(key); else { return map.put(key, value);

25 remove(key, value) if (map.containskey(key) && map.get(key).equals(value)) { map.remove(key); return true; else { return false;

26 replace(key, oldval, newval) if (map.containskey(key) && map.get(key).equals(oldval)) { map.put(key, newval); return true; else { return false;

27 Compare and Set ConcurrentMap<Object, Integer> counthits = new ConcurrentHashMap<>(); private void incrementcount(object key) { Integer oldval, newval; do { oldval = counthits.get(key); newval = (oldval==null)? 1: (oldval + 1); while (!counthits.replace(key, oldval, newval));

28 Atomic Primitives AtomicBoolean AtomicInteger AtomicLong AtomicReference<V>

29 AtomicInteger (1) class Counter { private int c = 0; public void increment() { c++; public void decrement() { c--; public int value() { return c; Fine in a single thread, not so much multi-threaded

30 AtomicInteger (2) class Counter { private volatile int c = 0; public void increment() { c++; public void decrement() { c--; public int value() { return c; If you do this, I will look up your contact info, find your next of kin, and personally tell them how disappointed I am in you.

31 AtomicInteger (3) class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; public synchronized void decrement() { c--; public synchronized int value() { return c; Does the job, but gets trickier for less trivial code

32 AtomicInteger (4) import java.util.concurrent.atomic.atomicinteger; class AtomicCounter { private AtomicInteger c = new AtomicInteger(0); public void increment() { c.incrementandget(); public void decrement() { c.decrementandget(); public int value() { return c.get();

33 Thread Safe Iteration ConcurrentMap<Object, Object> chm = new ConcurrentHashMap<>(); for (Iterator it = chm.iterator(); it.hasnext(); ) { dosomething(it.next()); Iterators are weakly consistent: No ConcurrentModificationException is thrown Modifications and removals are visible Insertions may be visible, no guarantees

34 Performance The Concurrent collections: Parallel access > more efficient But: size() may be either not atomic, or not correct

35 CopyOnWriteArray[List Set] Use when: Care most about traversing the Collection Don t care about temp inconsistency putifabsent() sequentially scans the array Iterator.remove() not supported! Creates "snapshot" at Iterator creation

36 Queue Idea: list without random access, add in back, take from front LinkedList, basic implementation PriorityQueue, allow assigning priorities ConcurrentLinkedQueue, thread-safe, lockfree, does not block

37 Blocking Queue Wait until an item can be taken / free space appears, thread safe! Consumer-Producer ArrayBlockingQueue (bounded, FIFO) LinkedBlockingQueue (optionally bounded) SynchronousQueue (zero capacity) PriorityBlockingQueue (unbounded, priority)

38 Interruptible Methods E take() throws InterruptedException Blocking method How do stop waiting? Can be interrupted with Thread.interrupt() Only thread-owner should ever call this

39 Handling Calling Interruptible Method Propagate the InterruptedException Restore the interrupt: try { processtask(queue.take()); catch (InterruptedException e) { // Restore interrupted status! Thread.currentThread().interrupt();

40 Non-cancelable tasks public Task getnexttask(blockingqueue<task> queue) { boolean interrupted = false; try { while (true) { try { return queue.take(); catch (InterruptedException e) { interrupted = true; // fall through and retry finally { if (interrupted) Thread.currentThread().interrupt();

41 TimeUnit Convenient time conversions: TimeUnit.MILLISECONDS.convert(20L, TimeUnit.SECONDS); TimeUnit.SECONDS.toMillis(20L); Collections with timeouts: queue.offer(task,100l, TimeUnit.NANOSECONDS); Thread.sleep: TimeUnit.SECONDS.sleep(10L);

42 Concurrent Collections (Java 6) Interface ConcurrentNavigableMap: ConcurrentSkipListMap ConcurrentSkipListSet Replacements for respectively: Synchronised TreeMap Synchronised TreeSet

43 Deques Efficient insertion and removal from both the head and the tail Not thread safe basic implementations: LinkedList ArrayDeque

44 Blocking Deques LinkedBlockingDeque Thread safe Blocks Work stealing pattern

45 Concurrent Collections (Java 7) ConcurrentLinkedDeque Improved ConcurrentLinkedQueue Interface TransferQueue LinkedTransferQueue

46 TransferQueue interface TransferQueue<E> extends BlockingQueue<E> { boolean trytransfer(e e) void transfer(e e) throws InterruptedException boolean haswaitingconsumer() int getwaitingconsumercount()...

47 Synchronisers

48 Synchroniser is any object that coordinates the control flow of threads based on its state. Decide if an incoming thread can pass or has to wait.

49 Latch is a synchroniser that can delay the progress of threads until it reaches its terminal state. Acts as a gate, and remains open, once opened. Usages: Game lobby, waiting for all players to join Dependant services startup Resources initialisation

50 CountDownLatch class CountDownLatch { CountDownLatch(int count); void await(); void await(long timeout, TimeUnit unit); void countdown(); long getcount(); General idea: every incoming thread calls countdown(), then await(), until count is reached.

51 FutureTask class FutureTask<V> implements Future<V> { FutureTask(Callable<V> callable) FutureTask(Runnable r, V result) void run() V get()... interface Callable<V> { V call() Three states: waiting, running, done. Done is final again.

52 CompletableFuture (Java 8) class CompletableFuture<V> implements Future<V> { CompletableFuture<V> supplyasync(supplier<v> supplier) CompletableFuture<V> thenapply(function<? super T,? extends U> fn) CompletableFuture<Void> thenaccept( Consumer<? super T> action) boolean complete(t value) CompletableFuture<T> exceptionally(function<throwable,? extends T> fn)

53 CompletableFuture Chaining CompletableFuture.supplyAsync(this::findReceiver).thenApply(this::sendMsg).exceptionally(ex->new Result(Status.FAILED)).thenAccept(this::notify);

54 Semaphore (1) Counting semaphores are used to control the number of activities that can access a certain resource or perform a given action at the same time. Great to implement resource pools (e.g. database connectors). Can make any collection both blocking and bounded.

55 Semaphore (2) class Semaphore { Semaphore(int permits) void acquire() void release()... acquire() takes permit or blocks release() returns permit Basically, more flexible Lock

56 Barrier is a synchroniser that can delay the progress of threads until all parties have arrived. Generally: a Latch waits for events, a Barrier for threads.

57 CyclicBarrier class CyclicBarrier { CyclicBarrier(int parties) int await()... General idea: every incoming thread calls await(), when the nr of parties is reached, all threads are unblocked, and receive their arrival index. Usable multiple times (cyclic)

58 Taxonomy High level concurrency abstractions java.util.concurrent Low level locking synchronised blocks & java.util.concurrent.locks Low level primitives volatile, java.util.concurrent.atomic Data races: deliberate under-synchronisation Don t try it at home!

59 Summary Use concurrent collections over synchronised Use synchronisers instead of implementing your own low-level synchronisation Do not confuse: synchronised vs synchroniser

60 Recommended reading Java Concurrency in Practice, Brian Goetz

61 Homework assignment Implement a brute-force password cracker All details and code here: JavaFundamentalsZT/jf-hw-password-cracker When in doubt / have questions: jf@zeroturnaround.com Please note: you are all students at the highest educational institute of Estonia, act like it. If something is not 100% covered in the class, then do your own research!

62

63 Scalable Cache example public interface Computable<A, V> { V compute(a arg) throws InterruptedException; public class ExpensiveFunction implements Computable<String, BigInteger> { public BigInteger compute(string arg) { // after deep thought... return new BigInteger(arg);

64 public class Memoizer1<A, V> implements Computable<A, V> private final Map<A, V> cache = new HashMap<A, V>(); private final Computable<A, V> c; public Memoizer1(Computable<A, V> c) { this.c = c; public synchronized V compute(a arg) throws InterruptedException { V result = cache.get(arg); if (result == null) { result = c.compute(arg); cache.put(arg, result); return result;

65 Poor concurrency

66 public class Memoizer2<A, V> implements Computable<A, V> { private final Map<A, V> cache = new ConcurrentHashMap<A, V>(); private final Computable<A, V> c; public Memoizer2(Computable<A, V> c) { this.c = c; public V compute(a arg) throws InterruptedException { V result = cache.get(arg); if (result == null) { result = c.compute(arg); cache.put(arg, result); return result;

67 Computing duplicates

68 public class Memoizer3<A, V> implements Computable<A, V> {... public V compute(final A arg) throws InterruptedException { Future<V> f = cache.get(arg); if (f == null) { Callable<V> eval = new Callable<V>() { public V call() throws InterruptedException { return c.compute(arg); ; FutureTask<V> ft = new FutureTask<V>(eval); f = ft; cache.put(arg, ft); ft.run(); // call to c.compute happens here try { return f.get(); catch (ExecutionException e) { throw launderthrowable(e.getcause());

69 Still computing duplicates...

70 public V compute(final A arg) throws InterruptedException { while (true) { Future<V> f = cache.get(arg); if (f == null) { Callable<V> eval = new Callable<V>() {...; FutureTask<V> ft = new FutureTask<V>(eval); f = cache.putifabsent(arg, ft); if (f == null) { f = ft; ft.run(); try { return f.get(); catch (CancellationException e) { cache.remove(arg, f); catch (ExecutionException e) { throw launderthrowable(e.getcause());

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING)

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING) Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING) What is a Data Structure? Introduction A data structure is a particular way of organizing data using one or

More information

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

Do inner private classes maintain the thread-safety of the outer class CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREAD SAFETY] Retrospective on making a thread-safe class better! You may extend, but not always Depends, it does, on the code maze Is the fear of making things

More information

CONCURRENT API AND PARALLEL PROGRAMMING

CONCURRENT API AND PARALLEL PROGRAMMING MODULE 11 CONCURRENT API AND PARALLEL PROGRAMMING Module 11.A THREAD MODEL: RUNNABLE, CALLABLE, FUTURE, FUTURETASK Threads > What are threads? Threads are a virtual CPU. > The three parts of at thread

More information

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

More thread safety and Concurrent collections. Nasser Giacaman CompSci 230: Software Design and Construction 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

More information

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

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming. Lecture 07: Advanced Thread programming Software System Components 2 Behzad Bordbar School of Computer Science, University of Birmingham, UK Recap How to deal with race condition in Java Using synchronised

More information

Practical Concurrency. Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Practical Concurrency. Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Practical Concurrency Agenda Motivation Java Memory Model Basics Common Bug Patterns JDK Concurrency Utilities Patterns of Concurrent Processing Testing Concurrent Applications Concurrency in Java 7 2

More information

COMP 322: Fundamentals of Parallel Programming

COMP 322: Fundamentals of Parallel Programming COMP 322: Fundamentals of Parallel Programming https://wiki.rice.edu/confluence/display/parprog/comp322 Lecture 30: Advanced locking in Java Vivek Sarkar Department of Computer Science Rice University

More information

The Java FutureTask. Douglas C. Schmidt

The Java FutureTask. Douglas C. Schmidt The Java FutureTask Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning Objectives

More information

-Aditya Bhave CSCI-5448 Graduate Presentation

-Aditya Bhave CSCI-5448 Graduate Presentation -Aditya Bhave CSCI-5448 Graduate Presentation 04-01-2011 MSEE at CU finishing up in Summer 11 Work full time at Alticast Inc Background in Embedded Systems Media Processing Middleware Cable TV industry

More information

Simpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0

Simpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0 Simpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0 Brian Goetz Principal Consultant, Quiotix Corp David Holmes Staff Engineer, Sun Microsystems, Inc. TS-4915 2006 JavaOne SM Conference

More information

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

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem COMP 322: Fundamentals of Parallel Programming Lecture 30: Java Synchronizers, Dining Philosophers Problem Vivek Sarkar, Shams Imam Department of Computer Science, Rice University Contact email: vsarkar@rice.edu,

More information

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

Threads and Locks, Part 2. CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014 Threads and Locks, Part 2 CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014 1 Goals Cover the material presented in Chapter 2 of our concurrency textbook In particular, selected material

More information

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

Common Java Concurrency pitfalls. Presented by : Kunal Sinha Austin Java Users Group 03/26/2019 Common Java Concurrency pitfalls Presented by : Kunal Sinha Austin Java Users Group 03/26/2019 About me Seasoned software engineer primarily working in the area of Identity and access management. Spent

More information

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

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: concurrency Outline Java threads thread implementation sleep, interrupt, and join threads that return values Thread synchronization

More information

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

Java theory and practice: Going atomic The new atomic classes are the hidden gems of java.util.concurrent 1 of 8 Java theory and practice: Going atomic The new atomic classes are the hidden gems of java.util.concurrent Level: Intermediate Brian Goetz (brian@quiotix.com), Principal Consultant, Quiotix 23 Nov

More information

The New Java Technology Memory Model

The New Java Technology Memory Model The New Java Technology Memory Model java.sun.com/javaone/sf Jeremy Manson and William Pugh http://www.cs.umd.edu/~pugh 1 Audience Assume you are familiar with basics of Java technology-based threads (

More information

Threads and Java Memory Model

Threads and Java Memory Model Threads and Java Memory Model Oleg Šelajev @shelajev oleg@zeroturnaround.com October 6, 2014 Agenda Threads Basic synchronization Java Memory Model Concurrency Concurrency - several computations are executing

More information

Chapter 32 Multithreading and Parallel Programming

Chapter 32 Multithreading and Parallel Programming Chapter 32 Multithreading and Parallel Programming 1 Objectives To get an overview of multithreading ( 32.2). To develop task classes by implementing the Runnable interface ( 32.3). To create threads to

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

Intro to multi-threaded programming in Java

Intro to multi-threaded programming in Java jonas.kvarnstrom@liu.se 2015 Intro to multi-threaded programming in Java Intro 1: Multitasking Most operating systems allow multitasking Multiple tasks are run in parallel (given enough processor cores)

More information

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

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data Lecture 4 Monitors Summary Semaphores Good news Simple, efficient, expressive Passing the Baton any await statement Bad news Low level, unstructured omit a V: deadlock omit a P: failure of mutex Synchronisation

More information

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

Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency Java Threads Vs Processes CS6868 - Concurrent Programming Java Concurrency V. Krishna Nandivada Typically each instance of JVM creates a single process. Each process creates one or more threads. Main thread

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff Collections by Vlad Costel Ungureanu for Learn Stuff Collections 2 Collections Operations Add objects to the collection Remove objects from the collection Find out if an object (or group of objects) is

More information

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Copyright 2012, Oracle and/or its affiliates. All rights reserved. 1 Field guide to Java collections Mike Duigou (@mjduigou) Java Core Libraries 2 Required Reading Should have used most at some point List, Vector, ArrayList, LinkedList, Arrays.asList Set, HashSet, TreeSet

More information

Lecture 16: Thread Safety in Java

Lecture 16: Thread Safety in Java COMP 150-CCP Concurrent Programming Lecture 16: Thread Safety in Java Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming March 13, 2008 Reference The content of this lecture is based on Chapter

More information

Fundamental language mechanisms

Fundamental language mechanisms Java Fundamentals Fundamental language mechanisms The exception mechanism What are exceptions? Exceptions are exceptional events in the execution of a program Depending on how grave the event is, the program

More information

Atomicity CS 2110 Fall 2017

Atomicity CS 2110 Fall 2017 Atomicity CS 2110 Fall 2017 Parallel Programming Thus Far Parallel programs can be faster and more efficient Problem: race conditions Solution: synchronization Are there more efficient ways to ensure the

More information

Data Structures & Concurrency

Data Structures & Concurrency Data Structures & Concurrency Issues with Old Collections Locking provides thread-safety, but... Often limits concurrent access Multiple operations can t happen at the same time Result safe but not scalable

More information

CS11 Java. Fall Lecture 7

CS11 Java. Fall Lecture 7 CS11 Java Fall 2006-2007 Lecture 7 Today s Topics All about Java Threads Some Lab 7 tips Java Threading Recap A program can use multiple threads to do several things at once A thread can have local (non-shared)

More information

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 2 (Can't live with it, can't 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. Principles of Software Construction: Objects, Design and Concurrency 15-214 toad The Perils of Concurrency, Part 2 (Can't live with it, can't live without it.) Spring 2013 Christian Kästner Charlie Garrod

More information

Advanced MEIC. (Lesson #18)

Advanced MEIC. (Lesson #18) Advanced Programming @ MEIC (Lesson #18) Last class Data races Java Memory Model No out-of-thin-air values Data-race free programs behave as expected Today Finish with the Java Memory Model Introduction

More information

Collections Questions

Collections Questions Collections Questions https://www.journaldev.com/1330/java-collections-interview-questions-and-answers https://www.baeldung.com/java-collections-interview-questions https://www.javatpoint.com/java-collections-interview-questions

More information

Phaser volle Energie...

Phaser volle Energie... Phaser volle Energie...... eine Reise ins Paralleluniversum von JDK7 Hartmut Lang, Ericsson July 2011 Hartmut Lang Senior Software Developer Solution Architect Network Management and Customer Solutions

More information

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

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections Thread Safety Today o Confinement o Threadsafe datatypes Required reading Concurrency Wrapper Collections Optional reading The material in this lecture and the next lecture is inspired by an excellent

More information

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

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 13 Robert Grimm, New York University 1 Review Last week Exceptions 2 Outline Concurrency Discussion of Final Sources for today s lecture: PLP, 12

More information

Java Barrier Synchronizers: CyclicBarrier (Part 1)

Java Barrier Synchronizers: CyclicBarrier (Part 1) Java Barrier Synchronizers: CyclicBarrier (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville,

More information

Concurrency Utilities: JSR-166

Concurrency Utilities: JSR-166 Concurrency Concurrency Utilities: JSR-166 Enables development of simple yet powerful multi-threaded applications > Like Collection provides rich data structure handling capability Beat C performance in

More information

5/23/2015. Core Java Syllabus. VikRam ShaRma

5/23/2015. Core Java Syllabus. VikRam ShaRma 5/23/2015 Core Java Syllabus VikRam ShaRma Basic Concepts of Core Java 1 Introduction to Java 1.1 Need of java i.e. History 1.2 What is java? 1.3 Java Buzzwords 1.4 JDK JRE JVM JIT - Java Compiler 1.5

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Threads Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent

More information

Models of concurrency & synchronization algorithms

Models of concurrency & synchronization algorithms Models of concurrency & synchronization algorithms Lecture 3 of TDA383/DIT390 (Concurrent Programming) Carlo A. Furia Chalmers University of Technology University of Gothenburg SP3 2016/2017 Today s menu

More information

Java Concurrency For Humans. Cay Horstmann Author of Core Java (10 editions since 1996)

Java Concurrency For Humans. Cay Horstmann Author of Core Java (10 editions since 1996) Java Concurrency For Humans Cay Horstmann Author of Core Java (10 editions since 1996) Outline Audience: Application programmers Goal: Modern Concurrency Constructs Executors and Futures Asynchronous Processing

More information

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. Cant live without it. Principles of Software Construction: Objects, Design and Concurrency 15-214 toad The Perils of Concurrency, Part 2 Can't live with it. Cant live without it. Fall 2013 Jonathan Aldrich Charlie Garrod School

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Quiz 1: What is printed? (Java) class MyTask implements Runnable { public void

More information

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms

More information

Synchronizers Latches & Barriers

Synchronizers Latches & Barriers Synchronizers Latches & Barriers Synchronizers A synchronizer is any object that coordinates the control of threads based on its state. The basic mechanisms in java.util.concurrent are: Latches: gate,

More information

Concurrency in Java Prof. Stephen A. Edwards

Concurrency in Java Prof. Stephen A. Edwards Concurrency in Java Prof. Stephen A. Edwards The Java Language Developed by James Gosling et al. at Sun Microsystems in the early 1990s Originally called Oak, first intended application was as an OS for

More information

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova Chair of Software Engineering Java and C# in Depth Prof. Dr. Bertrand Meyer Exercise Session 8 Nadia Polikarpova Quiz 1: What is printed? (Java) class MyTask implements Runnable { «Everything is ok! public

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Java 8 release date Was early September 2013 Currently moved to March 2014 http://openjdk.java.net/projects/jdk8/milestones

More information

TEST CONCURRENT PROGRAMMING. code: date: 19 June 2015 time:

TEST CONCURRENT PROGRAMMING. code: date: 19 June 2015 time: TEST CONCURRENT PROGRAMMING code: 01400537 date: 19 June 015 time: 13.45 16.45 - This is an open book examination. You are allowed to have a copy of Java Concurrency in Practice, and a copy of the (unannotated)

More information

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 11 Synchronisation in Java II Natasha Alechina School of Computer Science nza@cs.nott.ac.uk Outline of this lecture Mutual exclusion in Java continued (next lecture:

More information

CSC Java Programming, Fall Java Data Types and Control Constructs

CSC Java Programming, Fall Java Data Types and Control Constructs CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference

More information

Midterm #1. CMSC 433: Programming Language Technologies and Paradigms. October 14, 2013

Midterm #1. CMSC 433: Programming Language Technologies and Paradigms. October 14, 2013 Midterm #1 CMSC 433: Programming Language Technologies and Paradigms October 14, 2013 Name Instructions Do not start until told to do so! This exam has 10 double-sided pages (including this one); make

More information

Java Platform Concurrency Gotchas

Java Platform Concurrency Gotchas Java Platform Concurrency Gotchas Alex Miller Terracotta Questions to answer > What are common concurrency problems? > Why are they problems? > How do I detect these problems? > How do I correct these

More information

Java Barrier Synchronizers: CountDownLatch (Part 1)

Java Barrier Synchronizers: CountDownLatch (Part 1) Java Barrier Synchronizers: CountDownLatch (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville,

More information

Synchronization SPL/2010 SPL/20 1

Synchronization SPL/2010 SPL/20 1 Synchronization 1 Overview synchronization mechanisms in modern RTEs concurrency issues places where synchronization is needed structural ways (design patterns) for exclusive access 2 Overview synchronization

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

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

Concurrency in Object Oriented Programs 4. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Concurrency in Object Oriented Programs 4 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Outline Thread Control Tasks and Task Control Finding and Exploiting Parallelism

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

Josh Bloch Charlie Garrod Darya Melicher

Josh Bloch Charlie Garrod Darya Melicher Principles of Software Construction: Objects, Design, and Concurrency Concurrency part 3 Concurrent classes and libraries Josh Bloch Charlie Garrod Darya Melicher 1 Administrivia Homework 5b due 11:59

More information

Concurrency, Thread. Dongkun Shin, SKKU

Concurrency, Thread. Dongkun Shin, SKKU Concurrency, Thread 1 Thread Classic view a single point of execution within a program a single PC where instructions are being fetched from and executed), Multi-threaded program Has more than one point

More information

Parallel Programming Practice

Parallel Programming Practice Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class

More information

Lecture 29: Java s synchronized statement

Lecture 29: Java s synchronized statement COMP 322: Fundamentals of Parallel Programming Lecture 29: Java s synchronized statement Vivek Sarkar Department of Computer Science, Rice University vsarkar@rice.edu https://wiki.rice.edu/confluence/display/parprog/comp322

More information

Generics. IRS W-9 Form

Generics. IRS W-9 Form Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]

More information

CSE Lecture 25: Concurrency 27 April Nate Nystrom UTA

CSE Lecture 25: Concurrency 27 April Nate Nystrom UTA CSE 5317 Lecture 25: Concurrency 27 April 2010 Nate Nystrom UTA Resources Doug Lea Java Concurrency in Practice Maurice Herlihy & Nir Shavit The Art of Multiprocessor Programming Concurrency Concurrency

More information

Parallel Programming Practice

Parallel Programming Practice Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class

More information

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

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Concurrency in Object Oriented Programs 1 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Outline Concurrency: the Future of Computing Java Concurrency Thread Safety

More information

Only one thread can own a specific monitor

Only one thread can own a specific monitor Java 5 Notes Threads inherit their priority and daemon properties from their creating threads The method thread.join() blocks and waits until the thread completes running A thread can have a name for identification

More information

Refactoring Sequential Java Code for Concurrency via Concurrent Libraries

Refactoring Sequential Java Code for Concurrency via Concurrent Libraries Refactoring Sequential Java Code for Concurrency via Concurrent Libraries Danny Dig (MIT UPCRC Illinois) John Marrero (MIT) Michael D. Ernst (MIT U of Washington) ICSE 2009 The Shift to Multicores Demands

More information

The Java Collections Framework. Chapters 7.5

The Java Collections Framework. Chapters 7.5 The Java s Framework Chapters 7.5 Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework Outline Introduction to the Java s Framework Iterators Interfaces,

More information

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects CMSC 433 Programming Language Technologies and Paradigms Composing Objects Composing Objects To build systems we often need to Create thread safe objects Compose them in ways that meet requirements while

More information

MODULE 6q - Exceptions

MODULE 6q - Exceptions MODULE 6q - Exceptions THE TRY-CATCH CONSTRUCT Three different exceptions are referred to in the program below. They are the ArrayIndexOutOfBoundsException which is built-into Java and two others, BadLuckException

More information

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark Multithreading Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark jbb@stll.au..dk Submission & Peer feedback peergrade.io/join AJJ452 What is going on here? Multithreading Threads

More information

CST242 Concurrency Page 1

CST242 Concurrency Page 1 CST242 Concurrency Page 1 1 2 3 4 5 6 7 9 Concurrency CST242 Concurrent Processing (Page 1) Only computers with multiple processors can truly execute multiple instructions concurrently On single-processor

More information

Java Collections Framework

Java Collections Framework Java Collections Framework Introduction In this article from my free Java 8 course, you will be given a high-level introduction of the Java Collections Framework (JCF). The term Collection has several

More information

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages The Dining Philosophers Problem CMSC 0: Organization of Programming Languages Threads Classic Concurrency Problems Philosophers either eat or think They must have two forks to eat Can only use forks on

More information

Final Concurrency. Oleg October 27, 2014

Final Concurrency. Oleg October 27, 2014 Final Concurrency Oleg Šelajev @shelajev oleg@zeroturnaround.com October 27, 2014 Feedbacks Task Executors Fork-Join framework Completable Future Agenda 2 HOMEWORK 4 FEEDBACK THREAD LOCAL VARIABLES TASK

More information

Lecture 4. The Java Collections Framework

Lecture 4. The Java Collections Framework Lecture 4. The Java s Framework - 1 - Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework - 2 - Learning Outcomes From this lecture you should

More information

Process Synchronization

Process Synchronization Process Synchronization Concurrent access to shared data may result in data inconsistency Multiple threads in a single process Maintaining data consistency requires mechanisms to ensure the orderly execution

More information

Multithreading and Interactive Programs

Multithreading and Interactive Programs Multithreading and Interactive Programs CS160: User Interfaces John Canny. This time Multithreading for interactivity need and risks Some design patterns for multithreaded programs Debugging multithreaded

More information

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

Efficient Java (with Stratosphere) Arvid Heise, Large Scale Duplicate Detection Efficient Java (with Stratosphere) Arvid Heise, Large Scale Duplicate Detection Agenda 2 Bottlenecks Mutable vs. Immutable Caching/Pooling Strings Primitives Final Classloaders Exception Handling Concurrency

More information

Buffer & File Optimization. Cloud Databases DataLab CS, NTHU

Buffer & File Optimization. Cloud Databases DataLab CS, NTHU Buffer & File Optimization Cloud Databases DataLab CS, NTHU 1 Outline Useful Java Classes for Concurrency Lock Striping Summary of File & Buffer Optimization 2 Outline Useful Java Classes for Concurrency

More information

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

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 Session objectives Introduction Creating thread Thread class

More information

Concurrency WS 2010/2011 The Java Memory Model

Concurrency WS 2010/2011 The Java Memory Model Concurrency WS 2010/2011 The Java Memory Model Peter Thiemann November 2, 2010 Outline 1 Java Memory Model 2 Example Programs Java Memory Model Java does not guarantee linearizability or sequential consistency

More information

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

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks

More information

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

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Java SE 8 Programming

Java SE 8 Programming Java SE 8 Programming Training Calendar Date Training Time Location 16 September 2019 5 Days Bilginç IT Academy 28 October 2019 5 Days Bilginç IT Academy Training Details Training Time : 5 Days Capacity

More information

JAVA EXAMPLES - SOLVING DEADLOCK

JAVA EXAMPLES - SOLVING DEADLOCK JAVA EXAMPLES - SOLVING DEADLOCK http://www.tutorialspoint.com/javaexamples/thread_deadlock.htm Copyright tutorialspoint.com Problem Description: How to solve deadlock using thread? Solution: Following

More information

Core Java Syllabus. Overview

Core Java Syllabus. Overview Core Java Syllabus Overview Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java

More information

Java HashMap Interview Questions

Java HashMap Interview Questions Java HashMap Interview Questions codespaghetti.com/java-hashmap-interview-questions/ HashMap Java HashMap Interview Questions, Algorithms and Programs. Table of Contents: CHAPTER 1: Java HashMap Interview

More information

Atomic Variables & Nonblocking Synchronization

Atomic Variables & Nonblocking Synchronization Atomic Variables & Nonblocking Synchronization CMSC 433 Fall 2014 Michael Hicks (with some slides due to Rance Cleaveland) A Locking Counter public final class Counter { private long value = 0; public

More information

Resource management. Real-Time Systems. Resource management. Resource management

Resource management. Real-Time Systems. Resource management. Resource management Real-Time Systems Specification Implementation Verification Mutual exclusion is a general problem that exists at several levels in a real-time system. Shared resources internal to the the run-time system:

More information

Stuart

Stuart Clojure Time Stuart Halloway stu@clojure.com @stuarthalloway Copyright 2007-2010 Relevance, Inc. This presentation is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United

More information

Java SE 8 Programming

Java SE 8 Programming Oracle University Contact Us: +52 1 55 8525 3225 Java SE 8 Programming Duration: 5 Days What you will learn This Java SE 8 Programming training covers the core language features and Application Programming

More information

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

Learning from Bad Examples. CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014 Learning from Bad Examples CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014 1 Goals Demonstrate techniques to design for shared mutability Build on an example where multiple threads

More information

VERIFICATION OF SHARED-READING SYNCHRONISERS

VERIFICATION OF SHARED-READING SYNCHRONISERS VERIFICATION OF SHARED-READING SYNCHRONISERS MARIEKE HUISMAN UNIVERSITY OF TWENTE, NETHERLANDS JOINT WORK WITH AFSHIN AMIGHI AND STEFAN BLOM SOFTWARE RELIABILITY All software has errors! Software failures

More information

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

Principles of Software Construction: Objects, Design, and Concurrency. The Perils of Concurrency, Part 3 Can't live with it. Can't live without it. Principles of Software Construction: Objects, Design, and Concurrency The Perils of Concurrency, Part 3 Can't live with it. Can't live without it. Fall 2014 Charlie Garrod Jonathan Aldrich School of Computer

More information

A Comprehensive Study on the Energy Efficiency of Java Thread-Safe Collections. Fernando Castor

A Comprehensive Study on the Energy Efficiency of Java Thread-Safe Collections. Fernando Castor A Comprehensive Study on the Energy Efficiency of Java Thread-Safe Collections Gustavo Pinto Kenan Liu Fernando Castor David Liu 1 Disclaimer 2 Miguel turns 8mo today! 3 Motivations 4 First, energy consumption

More information

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer. CMSC 330: Organization of Programming Languages Threads Computation Abstractions t1 t2 t1 t3 t2 t1 p1 p2 p3 p4 CPU 1 CPU 2 A computer t4 t5 Processes (e.g., JVM s) Threads CMSC 330 2 Processes vs. Threads

More information

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information