SlideShare a Scribd company logo
Concurrent
Programming
07
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg
Recap so farโ€ฆ
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg
Previous Session
โ€ข Processes & Threads
โ€ข Thread Objects
โ€ข Defining & Starting a Thread
โ€ข Pausing Execution with Sleep
โ€ข Interrupts
โ€ข Joins
โ€ข The Simple Threads Example
โ€ข Synchronisation
โ€ข Thread Interference
โ€ข Memory Consistency Errors
Previous Session
Cont.d
โ€ข Synchronization
โ€ข Synchronised Methods
โ€ข Intrinsic Locks & Synchronisation
โ€ข Atomic Access
โ€ข Liveness
โ€ข Deadlock
โ€ข Starvation & Livestock
โ€ข Guarded Blocks
โ€ข Immutable Objects
โ€ข A Synchronized Class Example
โ€ข A Strategy for Defining Immutable Objects
Todayโ€ฆ
Todayโ€™s Session
โ€ข High Level Concurrency Objects
โ€ข Lock Objects
โ€ข Executors
โ€ข Executor Interfaces
โ€ข Thread Pools
โ€ข Fork/Join
โ€ข Concurrent Collections
โ€ข Atomic Variables
โ€ข Concurrent Random Numbers
โ€ข Questions & Exercises
High Level
Concurrency Objects
High Level Concurrency
Objects
โ€ข So far, this lesson has focused on the low-level APIs that have been part of the
Java platform from the very beginning.
โ€ข These APIs are adequate for very basic tasks, but higher-level building blocks
are needed for more advanced tasks.
โ€ข This is especially true for massively concurrent applications that fully exploit
today's multiprocessor and multi-core systems.
โ€ข In this section we'll look at some of the high-level concurrency features
introduced with version 5.0 of the Java platform.
โ€ข Most of these features are implemented in the new java.util.concurrent
packages.
โ€ข There are also new concurrent data structures in the Java Collections
Framework.
High Level Concurrency
Objects Cont.d
โ€ข Lock objects
โ€ข support locking idioms that simplify many concurrent applications.
โ€ข Executors
โ€ข define a high-level API for launching and managing threads.
โ€ข Executor implementations provided by java.util.concurrent provide thread pool management suitable for
large-scale applications.
โ€ข Concurrent collections
โ€ข make it easier to manage large collections of data, and can greatly reduce the need for synchronization.
โ€ข Atomic variables
โ€ข have features that minimize synchronization and help avoid memory consistency errors.
โ€ข ThreadLocalRandom
โ€ข (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.
Lock Objects
Lock Objects
โ€ข Synchronized code relies on a simple kind of reentrant lock.
โ€ข This kind of lock is easy to use, but has many limitations.
โ€ข More sophisticated locking idioms are supported by the
java.util.concurrent.locks package.
โ€ข We won't examine this package in detail, but instead will focus on its most
basic interface, Lock.
โ€ข Lock objects work very much like the implicit locks used by synchronized code.
โ€ข As with implicit locks, only one thread can own a Lock object at a time.
โ€ข Lock objects also support a wait/notify mechanism, through their associated
Condition objects.
Lock Objects Cont.d
โ€ข The biggest advantage of Lock objects over implicit locks is their ability to back out of an attempt to acquire
a lock.
โ€ข The tryLock method backs out if the lock is not available immediately or before a timeout expires (if
specified).
โ€ข The lockInterruptibly method backs out if another thread sends an interrupt before the lock is acquired.
โ€ข Let's use Lock objects to solve the deadlock problem we saw in Liveness.
โ€ข Tom and Jerry have trained themselves to notice when a friend is about to bow.
โ€ข We model this improvement by requiring that our Friend objects must acquire locks for both participants
before proceeding with the bow.
โ€ข Here is the source code for the improved model, Safelock.
โ€ข To demonstrate the versatility of this idiom,
โ€ข we assume that Tom and Jerry are so infatuated with their newfound ability to bow safely that they can't
stop bowing to each other:
Lock Objects Cont.d
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Random;
public class Safelock {
static class Friend {
private final String name;
private final Lock lock = new ReentrantLock();
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public boolean impendingBow(Friend bower) {
Boolean myLock = false;
Boolean yourLock = false;
try {
myLock = lock.tryLock();
yourLock = bower.lock.tryLock();
} finally {
if (! (myLock && yourLock)) {
if (myLock) {
lock.unlock();
}
if (yourLock) {
bower.lock.unlock();
}
}
}
return myLock && yourLock;
}
public void bow(Friend bower) {
if (impendingBow(bower)) {
try {
System.out.format("%s: %s has"
+ " bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
} finally {
lock.unlock();
bower.lock.unlock();
}
} else {
System.out.format("%s: %s started"
+ " to bow to me, but saw that"
+ " I was already bowing to"
+ " him.%n",
this.name, bower.getName());
}
}
public void bowBack(Friend bower) {
System.out.format("%s: %s has" +
" bowed back to me!%n",
this.name, bower.getName());
}
}
static class BowLoop implements Runnable {
private Friend bower;
private Friend bowee;
public BowLoop(Friend bower, Friend bowee) {
this.bower = bower;
this.bowee = bowee;
}
public void run() {
Random random = new Random();
for (;;) {
try {
Thread.sleep(random.nextInt(10));
} catch (InterruptedException e) {}
bowee.bow(bower);
}
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new BowLoop(alphonse, gaston)).start();
new Thread(new BowLoop(gaston, alphonse)).start();
}
}
Executors
Executors
โ€ข In all of the previous examples,
โ€ข there's a close connection between
โ€ข the task being done by a new thread,
โ€ข as defined by its Runnable object,
โ€ข and the thread itself,
โ€ข as defined by a Thread object.
โ€ข This works well for small applications, but in large-scale applications,
โ€ข it makes sense to separate thread management and creation from the rest of the
application.
โ€ข Objects that encapsulate these functions are known as executors.
Executors Cont.d
โ€ข The following subsections describe executors in
detail.
โ€ข Executor Interfaces define the three executor
object types.
โ€ข Thread Pools are the most common kind of
executor implementation.
โ€ข Fork/Join is a framework (new in JDK 7) for
taking advantage of multiple processors.
Executor Interfaces
โ€ข The java.util.concurrent package defines three executor interfaces:
โ€ข Executor,
โ€ข a simple interface that
โ€ข supports launching new tasks.
โ€ข ExecutorService,
โ€ข a subinterface of Executor, which
โ€ข adds features that help manage the lifecycle, both of the individual tasks and of the executor itself.
โ€ข ScheduledExecutorService,
โ€ข a subinterface of ExecutorService,
โ€ข supports future and/or periodic execution of tasks.
โ€ข Typically, variables that refer to executor objects are declared as one of these three interface types, not with
an executor class type.
The Executor Interface
โ€ข The Executor interface provides a single method, execute, designed to be a drop-in replacement for a
common thread-creation idiom.
โ€ข If r is a Runnable object, and e is an Executor object you can replace
โ€ข with
โ€ข However, the definition of execute is less specific.
โ€ข The low-level idiom creates a new thread and launches it immediately.
โ€ข Depending on the Executor implementation, execute may do the same thing, but is more likely to use an
existing worker thread to run r, or to place r in a queue to wait for a worker thread to become available.
(We'll describe worker threads in the section on Thread Pools.)
โ€ข The executor implementations in java.util.concurrent are designed to make full use of the more advanced
ExecutorService and ScheduledExecutorService interfaces, although they also work with the base Executor
interface.
(new Thread(r)).start();
e.execute(r);
The ExecutorService
Interface
โ€ข The ExecutorService interface supplements execute with a similar, but more versatile submit
method.
โ€ข Like execute, submit accepts Runnable objects,
โ€ข but also accepts Callable objects, which allow the task to return a value.
โ€ข The submit method returns a Future object,
โ€ข which is used to retrieve the Callable return value
โ€ข and to manage the status of both Callable and Runnable tasks.
โ€ข ExecutorService also provides methods for submitting large collections of Callable objects.
โ€ข Finally, ExecutorService provides a number of methods for managing the shutdown of the
executor.
โ€ข To support immediate shutdown, tasks should handle interrupts correctly.
The SceduledExecutorService
Interface
โ€ข The ScheduledExecutorService interface
โ€ข supplements the methods of its parent ExecutorService with
schedule,
โ€ข which executes a Runnable or Callable task after a specified
delay.
โ€ข In addition, the interface defines scheduleAtFixedRate and
scheduleWithFixedDelay,
โ€ข which executes specified tasks repeatedly, at defined
intervals.
Thread Pools
โ€ข Most of the executor implementations in java.util.concurrent use thread pools,
โ€ข which consist of worker threads.
โ€ข This kind of thread exists separately from the Runnable and Callable tasks it
executes
โ€ข and is often used to execute multiple tasks.
โ€ข Using worker threads minimizes the overhead due to thread creation.
โ€ข Thread objects use a significant amount of memory,
โ€ข and in a large-scale application,
โ€ข allocating and deallocating many thread objects
โ€ข creates a significant memory management overhead.
Thread Pools Cont.d
โ€ข One common type of thread pool is the fixed thread pool.
โ€ข This type of pool always has a specified number of threads
running;
โ€ข if a thread is somehow terminated while it is still in use,
โ€ข it is automatically replaced with a new thread.
โ€ข Tasks are submitted to the pool via an internal queue,
โ€ข which holds extra tasks whenever there are more
active tasks than threads.
Thread Pools Cont.d
โ€ข An important advantage of the fixed thread pool is that applications using it degrade
gracefully.
โ€ข To understand this, consider a web server application
โ€ข where each HTTP request is handled by a separate thread.
โ€ข If the application simply creates a new thread for every new HTTP request,
โ€ข and the system receives more requests than it can handle immediately,
โ€ข the application will suddenly stop responding to all requests
โ€ข when the overhead of all those threads exceed the capacity of the system.
โ€ข With a limit on the number of the threads that can be created,
โ€ข the application will not be servicing HTTP requests as quickly as they come in,
โ€ข but it will be servicing them as quickly as the system can sustain.
Thread Pools Cont.d
โ€ข A simple way to create an executor that uses a
fixed thread pool is
โ€ข to invoke the newFixedThreadPool factory
method in java.util.concurrent.Executors
โ€ข This class also provides the following factory
methods:
Thread Pools Cont.d
โ€ข The newCachedThreadPool method
โ€ข creates an executor with an expandable thread pool.
โ€ข This executor is suitable for applications that launch many short-lived tasks.
โ€ข The newSingleThreadExecutor method
โ€ข creates an executor
โ€ข that executes a single task at a time.
โ€ข Several factory methods are ScheduledExecutorService versions of the above executors.
โ€ข If none of the executors provided by the above factory methods meet your needs,
โ€ข constructing instances of java.util.concurrent.ThreadPoolExecutor
โ€ข or java.util.concurrent.ScheduledThreadPoolExecutor
โ€ข will give you additional options.
Fork / Join
โ€ข The fork/join framework is an implementation of the ExecutorService interface that helps you take
advantage of multiple processors.
โ€ข It is designed for work that can be broken into smaller pieces recursively.
โ€ข The goal is to use all the available processing power to enhance the performance of your
application.
โ€ข As with any ExecutorService implementation, the fork/join framework distributes tasks to worker
threads in a thread pool.
โ€ข The fork/join framework is distinct because it uses a work-stealing algorithm.
โ€ข Worker threads that run out of things to do can steal tasks from other threads that are still busy.
โ€ข The center of the fork/join framework is the ForkJoinPool class, an extension of the
AbstractExecutorService class.
โ€ข ForkJoinPool implements the core work-stealing algorithm and can execute ForkJoinTask
processes.
Basic Use
โ€ข The first step for using the fork/join framework is to write code that performs a segment of the work.
โ€ข Your code should look similar to the following pseudocode:
โ€ข Wrap this code in a ForkJoinTask subclass,
โ€ข typically using one of its more specialized types,
โ€ข either RecursiveTask (which can return a result) or RecursiveAction.
โ€ข After your ForkJoinTask subclass is ready,
โ€ข create the object that represents all the work to be done
โ€ข and pass it to the invoke() method of a ForkJoinPool instance.
if (my portion of the work is small enough)
do the work directly
else
split my work into two pieces
invoke the two pieces and wait for the results
Blurring for Clarity
โ€ข To understand how the fork/join framework works, consider the following example.
โ€ข Suppose that you want to blur an image.
โ€ข The original source image is represented by an array of integers,
โ€ข where each integer contains the color values for a single pixel.
โ€ข The blurred destination image is also represented by an integer array with the same size as the source.
โ€ข Performing the blur is accomplished by
โ€ข working through the source array one pixel at a time.
โ€ข Each pixel is averaged with its surrounding pixels (the red, green, and blue components are averaged),
โ€ข and the result is placed in the destination array.
โ€ข Since an image is a large array, this process can take a long time.
โ€ข You can take advantage of concurrent processing on multiprocessor systems
โ€ข by implementing the algorithm using the fork/join framework.
โ€ข Here is one possible implementation:
Blurring for Clarity Cont.dpublic class ForkBlur extends RecursiveAction {
private int[] mSource;
private int mStart;
private int mLength;
private int[] mDestination;
// Processing window size; should be odd.
private int mBlurWidth = 15;
public ForkBlur(int[] src, int start, int length, int[] dst) {
mSource = src;
mStart = start;
mLength = length;
mDestination = dst;
}
protected void computeDirectly() {
int sidePixels = (mBlurWidth - 1) / 2;
for (int index = mStart; index < mStart + mLength; index++) {
// Calculate average.
float rt = 0, gt = 0, bt = 0;
for (int mi = -sidePixels; mi <= sidePixels; mi++) {
int mindex = Math.min(Math.max(mi + index, 0),
mSource.length - 1);
int pixel = mSource[mindex];
rt += (float)((pixel & 0x00ff0000) >> 16)
/ mBlurWidth;
gt += (float)((pixel & 0x0000ff00) >> 8)
/ mBlurWidth;
bt += (float)((pixel & 0x000000ff) >> 0)
/ mBlurWidth;
}
// Reassemble destination pixel.
int dpixel = (0xff000000 ) |
(((int)rt) << 16) |
(((int)gt) << 8) |
(((int)bt) << 0);
mDestination[index] = dpixel;
}
}
โ€ฆ
Blurring for Clarity Cont.d
โ€ข Now you implement the abstract compute() method,
โ€ข which either performs the blur directly or splits it into two smaller tasks.
โ€ข A simple array length threshold helps determine whether the work is performed or split.
protected static int sThreshold = 100000;
protected void compute() {
if (mLength < sThreshold) {
computeDirectly();
return;
}
int split = mLength / 2;
invokeAll(new ForkBlur(mSource, mStart, split, mDestination),
new ForkBlur(mSource, mStart + split, mLength - split,
mDestination));
}
Blurring for Clarity Cont.d
โ€ข If the previous methods are in a subclass of the RecursiveAction class,
โ€ข then setting up the task to run in a ForkJoinPool is straightforward,
โ€ข and involves the following steps:
โ€ข Create a task that represents all of the work to be done.
โ€ข Create the ForkJoinPool that will run the task.
โ€ข Run the task.
// source image pixels are in src
// destination image pixels are in dst
ForkBlur fb = new ForkBlur(src, 0, src.length, dst);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(fb);
Standard Implementations
โ€ข Besides using the fork/join framework to implement custom algorithms for tasks to be performed
concurrently on a multiprocessor system (such as the ForkBlur.java example in the previous section),
โ€ข there are some generally useful features in Java SE which are already implemented using the fork/join
framework.
โ€ข One such implementation, introduced in Java SE 8, is used by the java.util.Arrays class for its
parallelSort() methods.
โ€ข These methods are similar to sort(), but leverage concurrency via the fork/join framework.
โ€ข Parallel sorting of large arrays is faster than sequential sorting when run on multiprocessor systems.
โ€ข However, how exactly the fork/join framework is leveraged by these methods is outside the scope of the
Java Tutorials.
โ€ข For this information, see the Java API documentation.
โ€ข Another implementation of the fork/join framework is used by methods in the java.util.streams package,
which is part of Project Lambda scheduled for the Java SE 8 release.
โ€ข For more information, see the Lambda Expressions section in java site.
Concurrent Collections
Concurrent Collections
โ€ข The java.util.concurrent package includes a number of additions to the Java Collections Framework.
โ€ข These are most easily categorized by the collection interfaces provided:
โ€ข BlockingQueue
โ€ข defines a first-in-first-out data structure that blocks or times out when you attempt to add to a
full queue, or retrieve from an empty queue.
โ€ข ConcurrentMap
โ€ข is a subinterface of java.util.Map that defines useful atomic operations.
โ€ข These operations remove or replace a key-value pair only if the key is present, or add a key-
value pair only if the key is absent.
โ€ข Making these operations atomic helps avoid synchronization.
โ€ข The standard general-purpose implementation of ConcurrentMap is ConcurrentHashMap,
which is a concurrent analog of HashMap.
Concurrent Collections
Cont.d
โ€ข ConcurrentNavigableMap
โ€ข is a subinterface of ConcurrentMap that supports approximate matches.
โ€ข The standard general-purpose implementation of ConcurrentNavigableMap
โ€ข is ConcurrentSkipListMap,
โ€ข which is a concurrent analog of TreeMap.
โ€ข All of these collections help avoid Memory Consistency Errors
โ€ข by defining a happens-before relationship between an operation
โ€ข that adds an object to the collection with subsequent operations
โ€ข that access or remove that object.
Atomic Variables
Atomic Variables
โ€ข The java.util.concurrent.atomic package defines classes that support atomic
operations on single variables.
โ€ข All classes have get and set methods that work like reads and writes on volatile
variables.
โ€ข That is, a set has a happens-before relationship with any subsequent get on the
same variable.
โ€ข The atomic compareAndSet method also has these memory consistency
features,
โ€ข as do the simple atomic arithmetic methods that apply to integer atomic
variables.
โ€ข To see how this package might be used, let's return to the Counter class we
originally used to demonstrate thread interference:
Atomic Variables Cont.d
class Counter {
private int c = 0;
public void increment() {
c++;
}
public void decrement() {
c--;
}
public int value() {
return c;
}
}
Atomic Variables Cont.d
โ€ข One way to make Counter safe from thread
interference
โ€ข is to make its methods synchronized, as in
SynchronizedCounter:
Atomic Variables Cont.d
class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
Atomic Variables Cont.d
โ€ข For this simple class, synchronization is an acceptable solution.
โ€ข But for a more complicated class,
โ€ข we might want to avoid the liveness impact of unnecessary
synchronization.
โ€ข Replacing the int field with an AtomicInteger
โ€ข allows us to prevent thread interference
โ€ข without resorting to synchronization, as in AtomicCounter:
Atomic Variables Cont.d
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();
}
}
Concurrent Random
Numbers
Concurrent Random
Numbers
โ€ข In JDK 7, java.util.concurrent includes a convenience class, ThreadLocalRandom,
โ€ข for applications that
โ€ข expect to use random numbers
โ€ข from multiple threads or ForkJoinTasks.
โ€ข For concurrent access, using ThreadLocalRandom
โ€ข instead of Math.random()
โ€ข results in less contention and, ultimately, better performance.
โ€ข All you need to do is
โ€ข call ThreadLocalRandom.current(),
โ€ข then call one of its methods to retrieve a random number.
โ€ข Here is one example:
int r = ThreadLocalRandom.current() .nextInt(4, 77);
Further Readingโ€ฆ
Moving Forward
โ€ข http://sourceforge.net/projects/javaconcurrenta/
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg
Questions & Exercises
Questions
โ€ข Can you pass a Thread object to
Executor.execute?
โ€ข Would such an invocation make sense?
Exercises
โ€ข Compile and run BadThreads.java:
โ€ข The application should print out "Mares do eat oats."
โ€ข Is it guaranteed to always do this?
โ€ข If not, why not?
โ€ข Would it help to change the parameters of the two invocations of Sleep?
โ€ข How would you guarantee that all changes to message will be visible in
the main thread?
โ€ข Modify the producer-consumer example in Guarded Blocks to use a
standard library class instead of the Drop class.
Exercisespublic class BadThreads {
static String message;
private static class CorrectorThread
extends Thread {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {}
// Key statement 1:
message = "Mares do eat oats.";
}
}
public static void main(String args[])
throws InterruptedException {
(new CorrectorThread()).start();
message = "Mares do not eat oats.";
Thread.sleep(2000);
// Key statement 2:
System.out.println(message);
}
}
Thank you.
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg

More Related Content

What's hot (20)

PDF
Java 8 - Stamped Lock
Haim Yadid
ย 
PPTX
Concurrency in Java
Allan Huang
ย 
PDF
Java Concurrency Gotchas
Alex Miller
ย 
PDF
[Java concurrency]01.thread management
xuehan zhu
ย 
PPTX
The Java memory model made easy
Rafael Winterhalter
ย 
PDF
Working With Concurrency In Java 8
Heartin Jacob
ย 
PPTX
Java concurrency - Thread pools
maksym220889
ย 
PDF
Concurrency Utilities in Java 8
Martin Toshev
ย 
PPTX
.NET Multithreading/Multitasking
Sasha Kravchuk
ย 
PPT
Java concurrency
ducquoc_vn
ย 
PPT
Java Multithreading and Concurrency
Rajesh Ananda Kumar
ย 
ODP
Multithreading 101
Tim Penhey
ย 
PPTX
Introduction to TPL
Gyuwon Yi
ย 
PPT
Java New Evolution
Allan Huang
ย 
PPTX
.NET: Thread Synchronization Constructs
Sasha Kravchuk
ย 
PPTX
Thread syncronization
priyabogra1
ย 
PPTX
Multi-Threading
Robert MacLean
ย 
PDF
Java Course 10: Threads and Concurrency
Anton Keks
ย 
PPTX
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Sachintha Gunasena
ย 
PDF
Java Multithreading Using Executors Framework
Arun Mehra
ย 
Java 8 - Stamped Lock
Haim Yadid
ย 
Concurrency in Java
Allan Huang
ย 
Java Concurrency Gotchas
Alex Miller
ย 
[Java concurrency]01.thread management
xuehan zhu
ย 
The Java memory model made easy
Rafael Winterhalter
ย 
Working With Concurrency In Java 8
Heartin Jacob
ย 
Java concurrency - Thread pools
maksym220889
ย 
Concurrency Utilities in Java 8
Martin Toshev
ย 
.NET Multithreading/Multitasking
Sasha Kravchuk
ย 
Java concurrency
ducquoc_vn
ย 
Java Multithreading and Concurrency
Rajesh Ananda Kumar
ย 
Multithreading 101
Tim Penhey
ย 
Introduction to TPL
Gyuwon Yi
ย 
Java New Evolution
Allan Huang
ย 
.NET: Thread Synchronization Constructs
Sasha Kravchuk
ย 
Thread syncronization
priyabogra1
ย 
Multi-Threading
Robert MacLean
ย 
Java Course 10: Threads and Concurrency
Anton Keks
ย 
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Sachintha Gunasena
ย 
Java Multithreading Using Executors Framework
Arun Mehra
ย 

Viewers also liked (11)

PDF
Java Programming - 07 java networking
Danairat Thanabodithammachari
ย 
PDF
Email Security Threats: IT Manager's Eyes Only
Topsec Technology
ย 
PDF
JEE Programming - 07 EJB Programming
Danairat Thanabodithammachari
ย 
PDF
Digital signatures
Ishwar Dayal
ย 
PPT
Digital signature
Hossain Md Shakhawat
ย 
PPT
Email
ARSD College
ย 
PPT
Digital Signature
saurav5884
ย 
PPT
Core java slides
Abhilash Nair
ย 
PPT
Electronic mail
Diwaker Pant
ย 
PPTX
Cisco Web and Email Security Overview
Cisco Security
ย 
PPT
Email Security and Awareness
Sanjiv Arora
ย 
Java Programming - 07 java networking
Danairat Thanabodithammachari
ย 
Email Security Threats: IT Manager's Eyes Only
Topsec Technology
ย 
JEE Programming - 07 EJB Programming
Danairat Thanabodithammachari
ย 
Digital signatures
Ishwar Dayal
ย 
Digital signature
Hossain Md Shakhawat
ย 
Email
ARSD College
ย 
Digital Signature
saurav5884
ย 
Core java slides
Abhilash Nair
ย 
Electronic mail
Diwaker Pant
ย 
Cisco Web and Email Security Overview
Cisco Security
ย 
Email Security and Awareness
Sanjiv Arora
ย 
Ad

Similar to Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock Objects, Executors, Concurrent Collections, Atomic Variables, Concurrent Random Numbers (20)

ODP
Concurrent Programming in Java
Ruben Inoto Soto
ย 
PPTX
Multi Threading
Ferdin Joe John Joseph PhD
ย 
KEY
Modern Java Concurrency (OSCON 2012)
Martijn Verburg
ย 
PPTX
Lecture 23-24.pptx
talha ijaz
ย 
PDF
Java concurrency
Abhijit Gaikwad
ย 
PDF
Concurrency-5.pdf
ssuser04005f
ย 
PPT
cs4240-multithreading.ppt presentation on multi threading
ShrutiPanda12
ย 
PPTX
Slide 7 Thread-1.pptx
ajmalhamidi1380
ย 
PPTX
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Sachintha Gunasena
ย 
PPT
Threads
RanjithaM32
ย 
DOCX
Threadnotes
Himanshu Rajput
ย 
PPTX
MULTITHREADING PROGRAMMING AND I/O THREAD
mohanrajm63
ย 
PDF
Java Threads: Lightweight Processes
Isuru Perera
ย 
PPTX
Multithreading and concurrency in android
Rakesh Jha
ย 
PDF
Other Approaches (Concurrency)
Sri Prasanna
ย 
PDF
Concurrency on the JVM
Bernhard Huemer
ย 
PPTX
Multithreading
sagsharma
ย 
PPT
Parallel programming
Swain Loda
ย 
KEY
Modern Java Concurrency
Ben Evans
ย 
PPTX
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
ย 
Concurrent Programming in Java
Ruben Inoto Soto
ย 
Multi Threading
Ferdin Joe John Joseph PhD
ย 
Modern Java Concurrency (OSCON 2012)
Martijn Verburg
ย 
Lecture 23-24.pptx
talha ijaz
ย 
Java concurrency
Abhijit Gaikwad
ย 
Concurrency-5.pdf
ssuser04005f
ย 
cs4240-multithreading.ppt presentation on multi threading
ShrutiPanda12
ย 
Slide 7 Thread-1.pptx
ajmalhamidi1380
ย 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Sachintha Gunasena
ย 
Threads
RanjithaM32
ย 
Threadnotes
Himanshu Rajput
ย 
MULTITHREADING PROGRAMMING AND I/O THREAD
mohanrajm63
ย 
Java Threads: Lightweight Processes
Isuru Perera
ย 
Multithreading and concurrency in android
Rakesh Jha
ย 
Other Approaches (Concurrency)
Sri Prasanna
ย 
Concurrency on the JVM
Bernhard Huemer
ย 
Multithreading
sagsharma
ย 
Parallel programming
Swain Loda
ย 
Modern Java Concurrency
Ben Evans
ย 
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
ย 
Ad

More from Sachintha Gunasena (16)

PPTX
Entrepreneurship and Commerce in IT - 14 - Web Marketing Communications
Sachintha Gunasena
ย 
PPTX
Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...
Sachintha Gunasena
ย 
PPTX
Entrepreneurship & Commerce in IT - 12 - Web Payments
Sachintha Gunasena
ย 
PPTX
Concurrency Programming in Java - 03 - Essentials of Java Part 2
Sachintha Gunasena
ย 
PPTX
Concurrency Programming in Java - 02 - Essentials of Java Part 1
Sachintha Gunasena
ย 
PPTX
Entrepreneurship & Commerce in IT - 11 - Security & Encryption
Sachintha Gunasena
ย 
PPTX
Entrepreneurship & Commerce in IT - 08 - E-Commerce business models and concepts
Sachintha Gunasena
ย 
PPTX
Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...
Sachintha Gunasena
ย 
PPTX
Entrepreneurship & Commerce in IT - 09 - The internet and the world wide web
Sachintha Gunasena
ย 
PPTX
Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...
Sachintha Gunasena
ย 
PPT
Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...
Sachintha Gunasena
ย 
PPT
Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...
Sachintha Gunasena
ย 
PPT
Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...
Sachintha Gunasena
ย 
PPT
Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...
Sachintha Gunasena
ย 
PPT
Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...
Sachintha Gunasena
ย 
PPT
Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...
Sachintha Gunasena
ย 
Entrepreneurship and Commerce in IT - 14 - Web Marketing Communications
Sachintha Gunasena
ย 
Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...
Sachintha Gunasena
ย 
Entrepreneurship & Commerce in IT - 12 - Web Payments
Sachintha Gunasena
ย 
Concurrency Programming in Java - 03 - Essentials of Java Part 2
Sachintha Gunasena
ย 
Concurrency Programming in Java - 02 - Essentials of Java Part 1
Sachintha Gunasena
ย 
Entrepreneurship & Commerce in IT - 11 - Security & Encryption
Sachintha Gunasena
ย 
Entrepreneurship & Commerce in IT - 08 - E-Commerce business models and concepts
Sachintha Gunasena
ย 
Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...
Sachintha Gunasena
ย 
Entrepreneurship & Commerce in IT - 09 - The internet and the world wide web
Sachintha Gunasena
ย 
Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...
Sachintha Gunasena
ย 
Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...
Sachintha Gunasena
ย 
Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...
Sachintha Gunasena
ย 
Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...
Sachintha Gunasena
ย 
Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...
Sachintha Gunasena
ย 
Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...
Sachintha Gunasena
ย 
Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...
Sachintha Gunasena
ย 

Recently uploaded (20)

PPTX
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
ย 
PPTX
Quality on Autopilot: Scaling Testing in Uyuni
Oscar Barrios Torrero
ย 
PPTX
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
ย 
PPTX
Seamless-Image-Conversion-From-Raster-to-wrt-rtx-rtx.pptx
Quick Conversion Services
ย 
PPTX
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
ย 
PDF
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
ย 
PPTX
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
ย 
PDF
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
ย 
PPTX
How Can Recruitment Management Software Improve Hiring Efficiency?
HireME
ย 
PDF
AI Software Development Process, Strategies and Challenges
Net-Craft.com
ย 
PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
ย 
PPTX
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
ย 
PDF
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
ย 
PDF
>Wondershare Filmora Crack Free Download 2025
utfefguu
ย 
PDF
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
PDF
Cloud computing Lec 02 - virtualization.pdf
asokawennawatte
ย 
PPTX
declaration of Variables and constants.pptx
meemee7378
ย 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
ย 
PDF
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
ย 
PPTX
For my supp to finally picking supp that work
necas19388
ย 
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
ย 
Quality on Autopilot: Scaling Testing in Uyuni
Oscar Barrios Torrero
ย 
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
ย 
Seamless-Image-Conversion-From-Raster-to-wrt-rtx-rtx.pptx
Quick Conversion Services
ย 
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
ย 
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
ย 
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
ย 
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
ย 
How Can Recruitment Management Software Improve Hiring Efficiency?
HireME
ย 
AI Software Development Process, Strategies and Challenges
Net-Craft.com
ย 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
ย 
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
ย 
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
ย 
>Wondershare Filmora Crack Free Download 2025
utfefguu
ย 
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
Cloud computing Lec 02 - virtualization.pdf
asokawennawatte
ย 
declaration of Variables and constants.pptx
meemee7378
ย 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
ย 
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
ย 
For my supp to finally picking supp that work
necas19388
ย 

Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock Objects, Executors, Concurrent Collections, Atomic Variables, Concurrent Random Numbers

  • 2. Recap so farโ€ฆ Sachintha Gunasena MBCS http://lk.linkedin.com/in/sachinthadtg
  • 3. Previous Session โ€ข Processes & Threads โ€ข Thread Objects โ€ข Defining & Starting a Thread โ€ข Pausing Execution with Sleep โ€ข Interrupts โ€ข Joins โ€ข The Simple Threads Example โ€ข Synchronisation โ€ข Thread Interference โ€ข Memory Consistency Errors
  • 4. Previous Session Cont.d โ€ข Synchronization โ€ข Synchronised Methods โ€ข Intrinsic Locks & Synchronisation โ€ข Atomic Access โ€ข Liveness โ€ข Deadlock โ€ข Starvation & Livestock โ€ข Guarded Blocks โ€ข Immutable Objects โ€ข A Synchronized Class Example โ€ข A Strategy for Defining Immutable Objects
  • 6. Todayโ€™s Session โ€ข High Level Concurrency Objects โ€ข Lock Objects โ€ข Executors โ€ข Executor Interfaces โ€ข Thread Pools โ€ข Fork/Join โ€ข Concurrent Collections โ€ข Atomic Variables โ€ข Concurrent Random Numbers โ€ข Questions & Exercises
  • 8. High Level Concurrency Objects โ€ข So far, this lesson has focused on the low-level APIs that have been part of the Java platform from the very beginning. โ€ข These APIs are adequate for very basic tasks, but higher-level building blocks are needed for more advanced tasks. โ€ข This is especially true for massively concurrent applications that fully exploit today's multiprocessor and multi-core systems. โ€ข In this section we'll look at some of the high-level concurrency features introduced with version 5.0 of the Java platform. โ€ข Most of these features are implemented in the new java.util.concurrent packages. โ€ข There are also new concurrent data structures in the Java Collections Framework.
  • 9. High Level Concurrency Objects Cont.d โ€ข Lock objects โ€ข support locking idioms that simplify many concurrent applications. โ€ข Executors โ€ข define a high-level API for launching and managing threads. โ€ข Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications. โ€ข Concurrent collections โ€ข make it easier to manage large collections of data, and can greatly reduce the need for synchronization. โ€ข Atomic variables โ€ข have features that minimize synchronization and help avoid memory consistency errors. โ€ข ThreadLocalRandom โ€ข (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.
  • 11. Lock Objects โ€ข Synchronized code relies on a simple kind of reentrant lock. โ€ข This kind of lock is easy to use, but has many limitations. โ€ข More sophisticated locking idioms are supported by the java.util.concurrent.locks package. โ€ข We won't examine this package in detail, but instead will focus on its most basic interface, Lock. โ€ข Lock objects work very much like the implicit locks used by synchronized code. โ€ข As with implicit locks, only one thread can own a Lock object at a time. โ€ข Lock objects also support a wait/notify mechanism, through their associated Condition objects.
  • 12. Lock Objects Cont.d โ€ข The biggest advantage of Lock objects over implicit locks is their ability to back out of an attempt to acquire a lock. โ€ข The tryLock method backs out if the lock is not available immediately or before a timeout expires (if specified). โ€ข The lockInterruptibly method backs out if another thread sends an interrupt before the lock is acquired. โ€ข Let's use Lock objects to solve the deadlock problem we saw in Liveness. โ€ข Tom and Jerry have trained themselves to notice when a friend is about to bow. โ€ข We model this improvement by requiring that our Friend objects must acquire locks for both participants before proceeding with the bow. โ€ข Here is the source code for the improved model, Safelock. โ€ข To demonstrate the versatility of this idiom, โ€ข we assume that Tom and Jerry are so infatuated with their newfound ability to bow safely that they can't stop bowing to each other:
  • 13. Lock Objects Cont.d import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.Random; public class Safelock { static class Friend { private final String name; private final Lock lock = new ReentrantLock(); public Friend(String name) { this.name = name; } public String getName() { return this.name; } public boolean impendingBow(Friend bower) { Boolean myLock = false; Boolean yourLock = false; try { myLock = lock.tryLock(); yourLock = bower.lock.tryLock(); } finally { if (! (myLock && yourLock)) { if (myLock) { lock.unlock(); } if (yourLock) { bower.lock.unlock(); } } } return myLock && yourLock; } public void bow(Friend bower) { if (impendingBow(bower)) { try { System.out.format("%s: %s has" + " bowed to me!%n", this.name, bower.getName()); bower.bowBack(this); } finally { lock.unlock(); bower.lock.unlock(); } } else { System.out.format("%s: %s started" + " to bow to me, but saw that" + " I was already bowing to" + " him.%n", this.name, bower.getName()); } } public void bowBack(Friend bower) { System.out.format("%s: %s has" + " bowed back to me!%n", this.name, bower.getName()); } } static class BowLoop implements Runnable { private Friend bower; private Friend bowee; public BowLoop(Friend bower, Friend bowee) { this.bower = bower; this.bowee = bowee; } public void run() { Random random = new Random(); for (;;) { try { Thread.sleep(random.nextInt(10)); } catch (InterruptedException e) {} bowee.bow(bower); } } } public static void main(String[] args) { final Friend alphonse = new Friend("Alphonse"); final Friend gaston = new Friend("Gaston"); new Thread(new BowLoop(alphonse, gaston)).start(); new Thread(new BowLoop(gaston, alphonse)).start(); } }
  • 15. Executors โ€ข In all of the previous examples, โ€ข there's a close connection between โ€ข the task being done by a new thread, โ€ข as defined by its Runnable object, โ€ข and the thread itself, โ€ข as defined by a Thread object. โ€ข This works well for small applications, but in large-scale applications, โ€ข it makes sense to separate thread management and creation from the rest of the application. โ€ข Objects that encapsulate these functions are known as executors.
  • 16. Executors Cont.d โ€ข The following subsections describe executors in detail. โ€ข Executor Interfaces define the three executor object types. โ€ข Thread Pools are the most common kind of executor implementation. โ€ข Fork/Join is a framework (new in JDK 7) for taking advantage of multiple processors.
  • 17. Executor Interfaces โ€ข The java.util.concurrent package defines three executor interfaces: โ€ข Executor, โ€ข a simple interface that โ€ข supports launching new tasks. โ€ข ExecutorService, โ€ข a subinterface of Executor, which โ€ข adds features that help manage the lifecycle, both of the individual tasks and of the executor itself. โ€ข ScheduledExecutorService, โ€ข a subinterface of ExecutorService, โ€ข supports future and/or periodic execution of tasks. โ€ข Typically, variables that refer to executor objects are declared as one of these three interface types, not with an executor class type.
  • 18. The Executor Interface โ€ข The Executor interface provides a single method, execute, designed to be a drop-in replacement for a common thread-creation idiom. โ€ข If r is a Runnable object, and e is an Executor object you can replace โ€ข with โ€ข However, the definition of execute is less specific. โ€ข The low-level idiom creates a new thread and launches it immediately. โ€ข Depending on the Executor implementation, execute may do the same thing, but is more likely to use an existing worker thread to run r, or to place r in a queue to wait for a worker thread to become available. (We'll describe worker threads in the section on Thread Pools.) โ€ข The executor implementations in java.util.concurrent are designed to make full use of the more advanced ExecutorService and ScheduledExecutorService interfaces, although they also work with the base Executor interface. (new Thread(r)).start(); e.execute(r);
  • 19. The ExecutorService Interface โ€ข The ExecutorService interface supplements execute with a similar, but more versatile submit method. โ€ข Like execute, submit accepts Runnable objects, โ€ข but also accepts Callable objects, which allow the task to return a value. โ€ข The submit method returns a Future object, โ€ข which is used to retrieve the Callable return value โ€ข and to manage the status of both Callable and Runnable tasks. โ€ข ExecutorService also provides methods for submitting large collections of Callable objects. โ€ข Finally, ExecutorService provides a number of methods for managing the shutdown of the executor. โ€ข To support immediate shutdown, tasks should handle interrupts correctly.
  • 20. The SceduledExecutorService Interface โ€ข The ScheduledExecutorService interface โ€ข supplements the methods of its parent ExecutorService with schedule, โ€ข which executes a Runnable or Callable task after a specified delay. โ€ข In addition, the interface defines scheduleAtFixedRate and scheduleWithFixedDelay, โ€ข which executes specified tasks repeatedly, at defined intervals.
  • 21. Thread Pools โ€ข Most of the executor implementations in java.util.concurrent use thread pools, โ€ข which consist of worker threads. โ€ข This kind of thread exists separately from the Runnable and Callable tasks it executes โ€ข and is often used to execute multiple tasks. โ€ข Using worker threads minimizes the overhead due to thread creation. โ€ข Thread objects use a significant amount of memory, โ€ข and in a large-scale application, โ€ข allocating and deallocating many thread objects โ€ข creates a significant memory management overhead.
  • 22. Thread Pools Cont.d โ€ข One common type of thread pool is the fixed thread pool. โ€ข This type of pool always has a specified number of threads running; โ€ข if a thread is somehow terminated while it is still in use, โ€ข it is automatically replaced with a new thread. โ€ข Tasks are submitted to the pool via an internal queue, โ€ข which holds extra tasks whenever there are more active tasks than threads.
  • 23. Thread Pools Cont.d โ€ข An important advantage of the fixed thread pool is that applications using it degrade gracefully. โ€ข To understand this, consider a web server application โ€ข where each HTTP request is handled by a separate thread. โ€ข If the application simply creates a new thread for every new HTTP request, โ€ข and the system receives more requests than it can handle immediately, โ€ข the application will suddenly stop responding to all requests โ€ข when the overhead of all those threads exceed the capacity of the system. โ€ข With a limit on the number of the threads that can be created, โ€ข the application will not be servicing HTTP requests as quickly as they come in, โ€ข but it will be servicing them as quickly as the system can sustain.
  • 24. Thread Pools Cont.d โ€ข A simple way to create an executor that uses a fixed thread pool is โ€ข to invoke the newFixedThreadPool factory method in java.util.concurrent.Executors โ€ข This class also provides the following factory methods:
  • 25. Thread Pools Cont.d โ€ข The newCachedThreadPool method โ€ข creates an executor with an expandable thread pool. โ€ข This executor is suitable for applications that launch many short-lived tasks. โ€ข The newSingleThreadExecutor method โ€ข creates an executor โ€ข that executes a single task at a time. โ€ข Several factory methods are ScheduledExecutorService versions of the above executors. โ€ข If none of the executors provided by the above factory methods meet your needs, โ€ข constructing instances of java.util.concurrent.ThreadPoolExecutor โ€ข or java.util.concurrent.ScheduledThreadPoolExecutor โ€ข will give you additional options.
  • 26. Fork / Join โ€ข The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. โ€ข It is designed for work that can be broken into smaller pieces recursively. โ€ข The goal is to use all the available processing power to enhance the performance of your application. โ€ข As with any ExecutorService implementation, the fork/join framework distributes tasks to worker threads in a thread pool. โ€ข The fork/join framework is distinct because it uses a work-stealing algorithm. โ€ข Worker threads that run out of things to do can steal tasks from other threads that are still busy. โ€ข The center of the fork/join framework is the ForkJoinPool class, an extension of the AbstractExecutorService class. โ€ข ForkJoinPool implements the core work-stealing algorithm and can execute ForkJoinTask processes.
  • 27. Basic Use โ€ข The first step for using the fork/join framework is to write code that performs a segment of the work. โ€ข Your code should look similar to the following pseudocode: โ€ข Wrap this code in a ForkJoinTask subclass, โ€ข typically using one of its more specialized types, โ€ข either RecursiveTask (which can return a result) or RecursiveAction. โ€ข After your ForkJoinTask subclass is ready, โ€ข create the object that represents all the work to be done โ€ข and pass it to the invoke() method of a ForkJoinPool instance. if (my portion of the work is small enough) do the work directly else split my work into two pieces invoke the two pieces and wait for the results
  • 28. Blurring for Clarity โ€ข To understand how the fork/join framework works, consider the following example. โ€ข Suppose that you want to blur an image. โ€ข The original source image is represented by an array of integers, โ€ข where each integer contains the color values for a single pixel. โ€ข The blurred destination image is also represented by an integer array with the same size as the source. โ€ข Performing the blur is accomplished by โ€ข working through the source array one pixel at a time. โ€ข Each pixel is averaged with its surrounding pixels (the red, green, and blue components are averaged), โ€ข and the result is placed in the destination array. โ€ข Since an image is a large array, this process can take a long time. โ€ข You can take advantage of concurrent processing on multiprocessor systems โ€ข by implementing the algorithm using the fork/join framework. โ€ข Here is one possible implementation:
  • 29. Blurring for Clarity Cont.dpublic class ForkBlur extends RecursiveAction { private int[] mSource; private int mStart; private int mLength; private int[] mDestination; // Processing window size; should be odd. private int mBlurWidth = 15; public ForkBlur(int[] src, int start, int length, int[] dst) { mSource = src; mStart = start; mLength = length; mDestination = dst; } protected void computeDirectly() { int sidePixels = (mBlurWidth - 1) / 2; for (int index = mStart; index < mStart + mLength; index++) { // Calculate average. float rt = 0, gt = 0, bt = 0; for (int mi = -sidePixels; mi <= sidePixels; mi++) { int mindex = Math.min(Math.max(mi + index, 0), mSource.length - 1); int pixel = mSource[mindex]; rt += (float)((pixel & 0x00ff0000) >> 16) / mBlurWidth; gt += (float)((pixel & 0x0000ff00) >> 8) / mBlurWidth; bt += (float)((pixel & 0x000000ff) >> 0) / mBlurWidth; } // Reassemble destination pixel. int dpixel = (0xff000000 ) | (((int)rt) << 16) | (((int)gt) << 8) | (((int)bt) << 0); mDestination[index] = dpixel; } } โ€ฆ
  • 30. Blurring for Clarity Cont.d โ€ข Now you implement the abstract compute() method, โ€ข which either performs the blur directly or splits it into two smaller tasks. โ€ข A simple array length threshold helps determine whether the work is performed or split. protected static int sThreshold = 100000; protected void compute() { if (mLength < sThreshold) { computeDirectly(); return; } int split = mLength / 2; invokeAll(new ForkBlur(mSource, mStart, split, mDestination), new ForkBlur(mSource, mStart + split, mLength - split, mDestination)); }
  • 31. Blurring for Clarity Cont.d โ€ข If the previous methods are in a subclass of the RecursiveAction class, โ€ข then setting up the task to run in a ForkJoinPool is straightforward, โ€ข and involves the following steps: โ€ข Create a task that represents all of the work to be done. โ€ข Create the ForkJoinPool that will run the task. โ€ข Run the task. // source image pixels are in src // destination image pixels are in dst ForkBlur fb = new ForkBlur(src, 0, src.length, dst); ForkJoinPool pool = new ForkJoinPool(); pool.invoke(fb);
  • 32. Standard Implementations โ€ข Besides using the fork/join framework to implement custom algorithms for tasks to be performed concurrently on a multiprocessor system (such as the ForkBlur.java example in the previous section), โ€ข there are some generally useful features in Java SE which are already implemented using the fork/join framework. โ€ข One such implementation, introduced in Java SE 8, is used by the java.util.Arrays class for its parallelSort() methods. โ€ข These methods are similar to sort(), but leverage concurrency via the fork/join framework. โ€ข Parallel sorting of large arrays is faster than sequential sorting when run on multiprocessor systems. โ€ข However, how exactly the fork/join framework is leveraged by these methods is outside the scope of the Java Tutorials. โ€ข For this information, see the Java API documentation. โ€ข Another implementation of the fork/join framework is used by methods in the java.util.streams package, which is part of Project Lambda scheduled for the Java SE 8 release. โ€ข For more information, see the Lambda Expressions section in java site.
  • 34. Concurrent Collections โ€ข The java.util.concurrent package includes a number of additions to the Java Collections Framework. โ€ข These are most easily categorized by the collection interfaces provided: โ€ข BlockingQueue โ€ข defines a first-in-first-out data structure that blocks or times out when you attempt to add to a full queue, or retrieve from an empty queue. โ€ข ConcurrentMap โ€ข is a subinterface of java.util.Map that defines useful atomic operations. โ€ข These operations remove or replace a key-value pair only if the key is present, or add a key- value pair only if the key is absent. โ€ข Making these operations atomic helps avoid synchronization. โ€ข The standard general-purpose implementation of ConcurrentMap is ConcurrentHashMap, which is a concurrent analog of HashMap.
  • 35. Concurrent Collections Cont.d โ€ข ConcurrentNavigableMap โ€ข is a subinterface of ConcurrentMap that supports approximate matches. โ€ข The standard general-purpose implementation of ConcurrentNavigableMap โ€ข is ConcurrentSkipListMap, โ€ข which is a concurrent analog of TreeMap. โ€ข All of these collections help avoid Memory Consistency Errors โ€ข by defining a happens-before relationship between an operation โ€ข that adds an object to the collection with subsequent operations โ€ข that access or remove that object.
  • 37. Atomic Variables โ€ข The java.util.concurrent.atomic package defines classes that support atomic operations on single variables. โ€ข All classes have get and set methods that work like reads and writes on volatile variables. โ€ข That is, a set has a happens-before relationship with any subsequent get on the same variable. โ€ข The atomic compareAndSet method also has these memory consistency features, โ€ข as do the simple atomic arithmetic methods that apply to integer atomic variables. โ€ข To see how this package might be used, let's return to the Counter class we originally used to demonstrate thread interference:
  • 38. Atomic Variables Cont.d class Counter { private int c = 0; public void increment() { c++; } public void decrement() { c--; } public int value() { return c; } }
  • 39. Atomic Variables Cont.d โ€ข One way to make Counter safe from thread interference โ€ข is to make its methods synchronized, as in SynchronizedCounter:
  • 40. Atomic Variables Cont.d class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } }
  • 41. Atomic Variables Cont.d โ€ข For this simple class, synchronization is an acceptable solution. โ€ข But for a more complicated class, โ€ข we might want to avoid the liveness impact of unnecessary synchronization. โ€ข Replacing the int field with an AtomicInteger โ€ข allows us to prevent thread interference โ€ข without resorting to synchronization, as in AtomicCounter:
  • 42. Atomic Variables Cont.d 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(); } }
  • 44. Concurrent Random Numbers โ€ข In JDK 7, java.util.concurrent includes a convenience class, ThreadLocalRandom, โ€ข for applications that โ€ข expect to use random numbers โ€ข from multiple threads or ForkJoinTasks. โ€ข For concurrent access, using ThreadLocalRandom โ€ข instead of Math.random() โ€ข results in less contention and, ultimately, better performance. โ€ข All you need to do is โ€ข call ThreadLocalRandom.current(), โ€ข then call one of its methods to retrieve a random number. โ€ข Here is one example: int r = ThreadLocalRandom.current() .nextInt(4, 77);
  • 46. Moving Forward โ€ข http://sourceforge.net/projects/javaconcurrenta/ Sachintha Gunasena MBCS http://lk.linkedin.com/in/sachinthadtg
  • 48. Questions โ€ข Can you pass a Thread object to Executor.execute? โ€ข Would such an invocation make sense?
  • 49. Exercises โ€ข Compile and run BadThreads.java: โ€ข The application should print out "Mares do eat oats." โ€ข Is it guaranteed to always do this? โ€ข If not, why not? โ€ข Would it help to change the parameters of the two invocations of Sleep? โ€ข How would you guarantee that all changes to message will be visible in the main thread? โ€ข Modify the producer-consumer example in Guarded Blocks to use a standard library class instead of the Drop class.
  • 50. Exercisespublic class BadThreads { static String message; private static class CorrectorThread extends Thread { public void run() { try { sleep(1000); } catch (InterruptedException e) {} // Key statement 1: message = "Mares do eat oats."; } } public static void main(String args[]) throws InterruptedException { (new CorrectorThread()).start(); message = "Mares do not eat oats."; Thread.sleep(2000); // Key statement 2: System.out.println(message); } }
  • 51. Thank you. Sachintha Gunasena MBCS http://lk.linkedin.com/in/sachinthadtg