Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Java.util.concurrent package. concurrency utilities packages provide a powerful, extensible framework of high-performance threading utilities such as."— Presentation transcript:

1 java.util.concurrent package

2 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.

3 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.

4 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

5 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

6 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.

7 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.

8 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)

9 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

10 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.

11 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.

12 How is CyclicBarrier?

13 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.


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

Similar presentations


Ads by Google