Concurrency Utilities: JSR-166

Similar documents
[module lab 1.2] STRUCTURING PROGRAMS IN TASKS

G52CON: Concepts of Concurrency

Parallel Programming Practice

CMSC 433 Programming Language Technologies and Paradigms Fall Locks & Conditions

Parallel Programming Practice

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

Concurrent Programming Benoît Garbinato

CSE Lecture 25: Concurrency 27 April Nate Nystrom UTA

The Java ExecutorService (Part 1)

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Final Concurrency. Oleg October 27, 2014

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

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

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

-Aditya Bhave CSCI-5448 Graduate Presentation

Threads Questions Important Questions

COMP 322: Fundamentals of Parallel Programming

Effective Concurrent Java. Brian Goetz Sr. Staff Engineer, Sun Microsystems

Charlie Garrod Bogdan Vasilescu

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

Multi-threading in Java. Jeff HUANG

F. Tip and M. Weintraub CONCURRENCY

CONCURRENT API AND PARALLEL PROGRAMMING

Chapter 8 Applying Thread Pools. Magnus Andersson

Only one thread can own a specific monitor

CST242 Concurrency Page 1

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

COMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization

Java ReentrantLock (Part 1)

SUMMARY FUTURES CALLABLES CONCURRENT PROGRAMMING THREAD S ADVANCED CONCEPTS

Daemon thread, 7 Deadlock, 27

Outline. Command Pattern. Examples. Goal & Applications Motivation (undo / redo) Structure & participants Sequence diagram

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

ECE 587 Hardware/Software Co-Design Lecture 07 Concurrency in Practice Shared Memory I

Producer/Consumer CSCI 201 Principles of Software Development

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

Threads and Parallelism in Java

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

Paradigmas de Computação Paralela

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

CS 159: Parallel Processing

Multithreading and Interactive Programs

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

Redis based In-Memory Data Grid and Distributed Locks in Java. Nikita Koksharov, Founder of Redisson

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

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

Buch gefunden? Im Blackboard eingetragen? Abgabe 1. Übung: , 23:59

Buffer & File Optimization. Cloud Databases DataLab CS, NTHU

COMP 322: Fundamentals of Parallel Programming

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

Multi-Threaded Programming Design CSCI 201 Principles of Software Development

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

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

Synchronization II: EventBarrier, Monitor, and a Semaphore. COMPSCI210 Recitation 4th Mar 2013 Vamsi Thummala

Northeastern University - Seattle CS5510 Professor Ian Gorton

Overview. Topics in This Section

Phaser volle Energie...

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Multiple Inheritance. Computer object can be viewed as

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

Chapter 32 Multithreading and Parallel Programming

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

System Programming. Practical Session 4: Threads and Concurrency / Safety

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Concurrency CSCI 201 Principles of Software Development

[module lab 1.3] CANCELLATION AND SHUTDOWN

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

G52CON: Concepts of Concurrency

CS 351 Design of Large Programs Threads and Concurrency

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

Atomicity CS 2110 Fall 2017

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

CSCD 330 Network Programming

Multithreading. Introduction and Basics. Classical Model. New Model. Summary. Multithreading Basics Problems with Multithreading

CPIT 305 Advanced Programming Multithreading

User Space Multithreading. Computer Science, University of Warwick

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

Lecture 03: Thread API (continue)

Programming in Java

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II. Threads in Java

Threads and Java Memory Model

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

1Z Java SE 7 Programmer II Exam Summary Syllabus Questions

JSR 236 Status Jan 28, 2013

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

Java Concurrency. Towards a better life By - -

JFokus Finding And Solving Java Deadlocks

CONCURRENCY IN JAVA Course Parallel Computing

CMSC 330: Organization of Programming Languages

Monitors CSCI 201 Principles of Software Development

Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

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

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004

Writing Parallel Programs COMP360

Charlie Garrod Michael Hilton

Multithreaded Programming in Java

Part IV Other Systems: I Java Threads

Transcription:

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 high-end server applications Provide richer set of concurrency building blocks > wait(), notify() and synchronized are too primitive Enhance scalability, performance, readability and thread safety of Java applications 2

Why Use Concurrency Utilities? Reduced programming effort Increased performance Increased reliability > Eliminate threading hazards such as deadlock, starvation, race conditions, or excessive context switching are eliminated Improved maintainability Increased productivity 3

Concurrency Utilities Task Scheduling Framework Callable's and Future's Synchronizers Concurrent Collections Atomic Variables Locks Nanosecond-granularity timing 4

Concurrency: Task Scheduling Framework

Task Scheduling Framework Executor/ExercuteService/Executors framework supports > standardizing invocation > scheduling > execution > control of asynchronous tasks according to a set of execution policies Executor is an interface ExecutorService extends Executor Executors is factory class for creating various kinds of ExercutorService implementations 6

Executor Interface Executor interface provides a way of decoupling task submission from the execution > execution: mechanics of how each task will be run, including details of thread use, scheduling Example Executor executor = getsomekindofexecutor(); executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2()); Many Executor implementations impose some sort of limitation on how and when tasks are scheduled 7

Executor and ExecutorService ExecutorService adds lifecycle management public interface Executor { void execute(runnable command); public interface ExecutorService extends Executor { void shutdown(); List<Runnable> shutdownnow(); boolean isshutdown(); boolean isterminated(); boolean awaittermination(long timeout, TimeUnit unit); // other convenience methods for submitting tasks 8

Creating ExecutorService From Executors public class Executors { static ExecutorService newsinglethreadedexecutor(); static ExecutorService newfixedthreadpool(int n); static ExecutorService newcachedthreadpool(); static ScheduledExecutorService newscheduledthreadpool(int n); // additional versions specifying ThreadFactory // additional utility methods 9

pre-j2se 5.0 Code Web Server poor resource management class WebServer { public static void main(string[] args) { ServerSocket socket = new ServerSocket(80); while (true) { final Socket connection = socket.accept(); Runnable r = new Runnable() { public void run() { handlerequest(connection); ; // Don't do this! new Thread(r).start(); 10

Executors Example Web Server better resource management class WebServer { Executor pool = Executors.newFixedThreadPool(7); public static void main(string[] args) { ServerSocket socket = new ServerSocket(80); while (true) { final Socket connection = socket.accept(); Runnable r = new Runnable() { public void run() { handlerequest(connection); ; pool.execute(r); 11

Concurrency: Callables and Futures

Callable's and Future's: Problem (pre-j2se 5.0) If a new thread (callable thread) is started in an application, there is currently no way to return a result from that thread to the thread (calling thread) that started it without the use of a shared variable and appropriate synchronization > This is complex and makes code harder to understand and maintain 13

Callables and Futures Callable thread (Callee) implements Callable interface > Implement call() method rather than run() Calling thread (Caller) submits Callable object to Executor and then moves on > Through submit() not execute() > The submit() returns a Future object Calling thread (Caller) then retrieves the result using get() method of Future object > If result is ready, it is returned > If result is not ready, calling thread will block 14

Build CallableExample (This is Callee) class CallableExample implements Callable<String> { public String call() { String result = The work is ended ; /* Do some work and create a result */ return result; 15

Future Example (Caller) ExecutorService es = Executors.newSingleThreadExecutor(); Future<String> f = es.submit(new CallableExample()); /* Do some work in parallel */ try { String callableresult = f.get(); catch (InterruptedException ie) { /* Handle */ catch (ExecutionException ee) { /* Handle */ 16

Concurrency: Synchronizers

Semaphores Typically used to restrict access to fixed size pool of resources New Semaphore object is created with same count as number of resources Thread trying to access resource calls aquire() > Returns immediately if semaphore count > 0 > Blocks if count is zero until release() is called by different thread > aquire() and release() are thread safe atomic operations 18

Semaphore Example private Semaphore available; private Resource[] resources; private boolean[] used; public Resource(int poolsize) { available = new Semaphore(poolSize); /* Initialise resource pool */ public Resource getresource() { try { available.aquire() catch (IE) { /* Acquire resource */ public void returnresource(resource r) { /* Return resource to pool */ available.release(); 19

Concurrency: Concurrent Collections

BlockingQueue Interface Provides thread safe way for multiple threads to manipulate collection ArrayBlockingQueue is simplest concrete implementation Full set of methods > put() > offer() [non-blocking] > peek() > take() > poll() [non-blocking and fixed time blocking] 21

Blocking Queue Example 1 private BlockingQueue<String> msgqueue; public Logger(BlockingQueue<String> mq) { msgqueue = mq; public void run() { try { while (true) { String message = msgqueue.take(); /* Log message */ catch (InterruptedException ie) { /* Handle */ 22

Blocking Queue Example 2 private ArrayBlockingQueue messagequeue = new ArrayBlockingQueue<String>(10); Logger logger = new Logger(messageQueue); public void run() { String somemessage; try { while (true) { /* Do some processing */ /* Blocks if no space available */ messagequeue.put(somemessage); catch (InterruptedException ie) { 23

Concurrency: Atomic Variables

Atomics java.util.concurrent.atomic > Small toolkit of classes that support lock-free thread-safe programming on single variables AtomicInteger balance = new AtomicInteger(0); public int deposit(integer amount) { return balance.addandget(amount); 25

Concurrency: Locks

Locks Lock interface > More extensive locking operations than synchronized block > No automatic unlocking use try/finally to unlock > Non-blocking access using trylock() ReentrantLock > Concrete implementation of Lock > Holding thread can call lock() multiple times and not block > Useful for recursive code 27

ReadWriteLock Has two locks controlling read and write access > Multiple threads can acquire the read lock if no threads have a write lock > If a thread has a read lock, others can acquire read lock but nobody can acquire write lock > If a thread has a write lock, nobody can have read/write lock > Methods to access locks rwl.readlock().lock(); rwl.writelock().lock(); 28

ReadWrite Lock Example class ReadWriteMap { final Map<String, Data> m = new TreeMap<String, Data>(); final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); final Lock r = rwl.readlock(); final Lock w = rwl.writelock(); public Data get(string key) { r.lock(); try { return m.get(key) finally { r.unlock(); public Data put(string key, Data value) { w.lock(); try { return m.put(key, value); finally { w.unlock(); public void clear() { w.lock(); try { m.clear(); finally { w.unlock(); 29