Java.util.concurrent package. concurrency utilities packages provide a powerful, extensible framework of high-performance threading utilities such as.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Monitors Chapter 7. The semaphore is a low-level primitive because it is unstructured. If we were to build a large system using semaphores alone, the.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
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 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
5.6 Semaphores Semaphores –Software construct that can be used to enforce mutual exclusion –Contains a protected variable Can be accessed only via wait.
5.6.2 Thread Synchronization with Semaphores Semaphores can be used to notify other threads that events have occurred –Producer-consumer relationship Producer.
Multithreaded Java COMP1681 / SE15 Introduction to Programming Fast Track Session 3.
02/23/2004CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
Java 5 Threading CSE301 University of Sunderland Harry Erwin, PhD.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 19 th, 2010 The University of Georgia.
Week 9 Building blocks.
Discussion Week 3 TA: Kyle Dewey. Overview Concurrency overview Synchronization primitives Semaphores Locks Conditions Project #1.
1 Advanced Computer Programming Concurrency Multithreaded Programs Copyright © Texas Education Agency, 2013.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Java Threads 1 1 Threading and Concurrent Programming in Java Queues D.W. Denbo.
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.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Synchronizing threads, thread pools, etc.
Kernel Locking Techniques by Robert Love presented by Scott Price.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
Java Threads 11 Threading and Concurrent Programming in Java Synchronization D.W. Denbo Synchronization D.W. Denbo.
4.1 Introduction to Threads Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads.
CSCI1600: Embedded and Real Time Software Lecture 17: Concurrent Programming Steven Reiss, Fall 2015.
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.
Asynchronous Programming Writing Asynchronous Code in Java SoftUni Team Technical Trainers Software University
Multithreading / Concurrency
Multi Threading.
PARALLEL PROGRAM CHALLENGES
Background on the need for Synchronization
Outline Other synchronization primitives
Principles of Operating Systems Lecture 11
Multithreaded Programming in Java
Critical sections, locking, monitors, etc.
Other Important Synchronization Primitives
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
23 Multithreading.
Monitors Chapter 7.
Threading And Parallel Programming Constructs
Multithreading.
Shared Memory Programming
Dr. Mustafa Cem Kasapbaşı
Semaphores Chapter 6.
Monitors Chapter 7.
Concurrency: Mutual Exclusion and Process Synchronization
Conditions for Deadlock
CSCI1600: Embedded and Real Time Software
Monitors Chapter 7.
- When you approach operating system concepts there might be several confusing terms that may look similar but in fact refer to different concepts:  multiprogramming, multiprocessing, multitasking,
NETWORK PROGRAMMING CNET 441
CSE 153 Design of Operating Systems Winter 19
CS333 Intro to Operating Systems
Threads and Multithreading
CSCI1600: Embedded and Real Time Software
“The Little Book on Semaphores” Allen B. Downey
EECE.4810/EECE.5730 Operating Systems
CSE 542: Operating Systems
Synchronization and liveness
Presentation transcript:

java.util.concurrent package

concurrency utilities packages provide a powerful, extensible framework of high-performance threading utilities such as thread pools and blocking queues. This package frees the programmer from the need to craft these utilities by hand, in much the same manner the collections framework did for data structures. Using the concurrency utilities, instead of developing components such as thread pools yourself, offers a number of advantages: 1.Reduced programming effort. 2.Increased performance. 3.Increased reliability. Developing concurrent classes is difficult -- the low-level concurrency primitives provided by the Java language (synchronized, volatile, wait(), notify(), and notifyAll()) are difficult to use correctly, and errors using these facilities can be difficult to detect and debug. 4.Improved maintainability. 5.Increased productivity.

concurrency utilities packages provide a powerful, extensible framework of high-performance threading utilities such as thread pools and blocking queues. This package frees the programmer from the need to craft these utilities by hand, in much the same manner the collections framework did for data structures. Using the concurrency utilities, instead of developing components such as thread pools yourself, offers a number of advantages: 1.Reduced programming effort. 2.Increased performance. 3.Increased reliability. Developing concurrent classes is difficult -- the low-level concurrency primitives provided by the Java language (synchronized, volatile, wait(), notify(), and notifyAll()) are difficult to use correctly, and errors using these facilities can be difficult to detect and debug. 4.Improved maintainability. 5.Increased productivity. Using the concurrency utilities to implement a concurrent application can help your program be clearer, shorter, faster, more reliable, more scalable, easier to write, easier to read, and easier to maintain.

What Concurrency Utilities has? 1.Task scheduling framework. The Executor interface standardizes invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.In a newly created thread, or in a thread pool, and developers can create customized implementations of Executor that support arbitrary execution policies.Executorthread poolExecutor 2.Fork/join framework. Based on the ForkJoinPool class, this framework is an implementation of Executor. It is designed to efficiently run a large number of tasks using a pool of worker threads.ForkJoinPool 3.Concurrent collections. Several new collections classes were added, including the new Queue, BlockingQueue and BlockingDeque interfaces.QueueBlockingQueueBlockingDeque 4.Atomic variables. Utility classes are provided that atomically manipulate single variables (primitive types or references), providing high- performance atomic arithmetic and compare-and-set methods. The atomic variable implementations in the java.util.concurrent.atomic like AtomicInteger, AtomicLong, etc…java.util.concurrent.atomic 5.Synchronizers. General purpose synchronization classes, including semaphores, barriers, latches, phasers, and exchangers, facilitate coordination between threads.semaphoresbarrierslatchesphasersexchangers 6.Locks. Though synchronized keyword, does locking, Lock in java.util.concurrent.locks package provides various Lock implementations like ReadWriteLock, DelayLock, etc…java.util.concurrent.locks

Locks support various methods for finer grained lock control, which are more expressive than implicit monitors (synchronized locks) A Lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock. Advantages of Lock over Synchronization The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way Lock implementations provide additional functionality over the use of synchronized methods and statements by providing a non- blocking attempt to acquire a lock (tryLock()), an attempt to acquire the lock that can be interrupted (lockInterruptibly(), and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)). A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as guaranteed ordering, non-reentrant usage, or deadlock detection

ReentrantLock: In simple terms, ReentrantLock allows an object to re-enter from one critical section to other critical section. Since you already have lock to enter one critical section, you can other critical section on same object by using current lock. ReentrantLock key features 1.Ability to lock interruptibly. 2.Ability to timeout while waiting for lock. 3.Power to create fair lock. 4.API to get list of waiting thread for lock. 5.Flexibility to try for lock without blocking. You can use ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock to further acquire control on granular locking on read and write operations.

Lock makes programmers life easier. Here are few situations that can be achieved easier with lock. Lock in one method, and release the lock in other method. You have two threads working on two different pieces of code, however first thread there is dependency on there second thread to complete certain piece of code before it proceed any further (while some other threads also working simultaneously). A shared lock can solve this problem quite easily. While, the lock, and conditions are build on the synchronized. So certainly you can achiever the same goal with that. However, that might make your life difficult and can deviate you from solving the actual problem.

Difference between Lock Interface and synchronized keyword The main differences between a Lock and a synchronized block are: 1) Having a timeout trying to get access to a synchronized block is not possible. Using Lock.tryLock(long timeout, TimeUnit timeUnit), it is possible. 2) The synchronized block must be fully contained within a single method. A Lock can have it’s calls to lock() andunlock() in separate methods.Lock.tryLock(long timeout, TimeUnit timeUnit)

Java.util.concurrent.atomic Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessity in multi-threaded environment to avoid data inconsistency. Let’s create a simple multi-threaded program where every thread increments the shared count variable 4 times. So if there are two threads, after they finish count value should be 8. Concurrency Framework provides Atomic classes for the primitive types. They are AtomicInteger, AtomicLong, AtomicBoolean

Java.util.concurrent.latch CountDownLatch is a high-level synchronization utility which is used to prevent a particular thread to start processing until all threads are ready. This is achieved by a countdown. The thread, which needs to wait for, starts with a counter, each thread them make the count down by 1 when they become ready, once the last thread call countDown() method, then the latch is broken and the thread waiting with counter starts running. Note that CountDownLatch starts with a fixed number of counts which cannot be changed later. There is another similar utility called CyclicBarrier, which can also be used in this situation, where one thread needs to wait for other threads before they start processing. Only difference between CyclicBarrier and CountDownLatch is that you can reuse the barrier even after its broker but you cannot reuse the count down latch, once count reaches to zero.

How CountDownLatch works? Create CountDownLatch and initialize with the count N. Other worker threads must have reference of latch object, because they will need to notify the CountDownLatch object that they have completed their task. This notification is done by countDown() method. Each time we call countDown() method, it decreases count of N. When all N threads have called this method, count reaches to zero and main thread is allowed to resume its execution.

How is CyclicBarrier?

What is Semaphore? java.util.concurrent.Semaphore is used to restrict the number of threads that can access a resource. That is, while synchronized allows only one thread to aquire lock and execute the synchronized block / method, Semaphore gives permission up to n threads to go and blocks the others. Semaphore provides two main method acquire() and release() for getting permits and releasing permits. acquire() method blocks until permit is available. Semaphore provides both blocking method as well as unblocking method to acquire permits.