SlideShare a Scribd company logo
1 of 51
Download to read offline
What is new in Java 8 Concurrency
T. Kishanthan
Technical Lead, WSO2
June 15, 2017
Agenda
โ— Java 8 - Lambda expressions, Streams
โ— Streams vs Parallel Streams
โ— Executor Framework
โ— Fork/Join Pool
โ— CompletableFuture
โ— ConcurrentHashMap Improvements
2
Java 8 Basics
Lambda
3
โ–ช A representation of an anonymous function which is passed
around.
โ–ช It doesnโ€™t have a name, but has a list of parameters, a body, a
return type.
Java 8 Basics
Lambda
4
Before:
Comparator<Apple> byWeight = new Comparator<Apple>() {
public int compare(Apple a1, Apple a2) {
return a1.getWeight().compareTo(a2.getWeight());
}
};
After:
Comparator<Apple> byWeight =
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
Java 8 Basics
Lambda
5
Before:
Runnable r2 = new Runnable() {
@Override
public void run() {
System.out.println("Hello Java Colombo!");
}
};
After:
Runnable r1 = () -> System.out.println("Hello Java Colombo!");
Java 8 Basics
Streams
6
โ€œA sequence of elements from a source that supports data
processing operations.โ€
Java 8 Basics
Streams
7
โ–ช Source - A data source such as collections, arrays, or I/O resources, where streams
consumes the elements.
โ–ช Sequence of elements - A stream provides a way to a get sequenced set of values of
a specific element type from a source. Collections are about data but streams are
about computations that applied on it.
โ–ช Data processing operations - Supports common set of operations like functional
programming languages to manipulate data, such as filter, map, reduce, find, sort,
etc. Operations can be executed either sequentially or in parallel.
Java 8 Basics
8
public static List<String> getLowCaloricDishesNamesInJava7(List<Dish> dishes) {
List<Dish> lowCaloricDishes = new ArrayList<>();
for (Dish d : dishes) {
if (d.getCalories() < 400) {
lowCaloricDishes.add(d);
}
}
List<String> lowCaloricDishesName = new ArrayList<>();
Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
public int compare(Dish d1, Dish d2) {
return Integer.compare(d1.getCalories(), d2.getCalories());
}
});
for (Dish d : lowCaloricDishes) {
lowCaloricDishesName.add(d.getName());
}
return lowCaloricDishesName;
}
Java 8 Basics
9
public static List<String> getLowCaloricDishesNamesInJava8(List<Dish> dishes) {
return dishes.stream()
.filter(d -> d.getCalories() < 400)
.sorted(comparing(Dish::getCalories))
.map(Dish::getName)
.collect(toList());
}
Java 8 Basics
Chaining stream operations forming a stream pipeline
10
Reference : Java 8 in Action - Lambdas, streams, and functional-style programming
Java 8 Basics
Chaining stream operations forming a stream pipeline
11
Demo
Streams vs Parallel Streams
โ–ช Parallel stream splits its data elements into multiple chunks, processing
each chunk with a different thread.
โ–ช Automatically partition the workload of a given operation on all the
cores of your multicore processor and keep all of them busy that
idling.
Streams vs Parallel Streams
โ–ช Sequential version
public static long sequentialSum(long n) {
return Stream.iterate(1L, i -> i + 1)
.limit(n)
.reduce(Long::sum)
.get();
}
Streams vs Parallel Streams
โ–ช Parallel version
public static long parallelSum(long n) {
return Stream.iterate(1L, i -> i + 1)
.limit(n)
.parallel()
.reduce(Long::sum)
.get();
}
Reference : Java 8 in Action - Lambdas, streams, and functional-style programming
Parallel Streams - Performance
Demo
Parallel Streams - Best Practices
โ–ช Automatic boxing and unboxing operations can dramatically hurt performance
โ–ช Some operations naturally perform worse on a parallel stream than on a
sequential stream
- findAny will perform better than findFirst - as no ordering is needed
โ–ช For small amount of data, using a parallel stream is not the correct choice
(almost)
โ–ช Parallel stream isnโ€™t always faster than the corresponding sequential version and
can sometimes work in a counterintuitive way
- check their performance with an appropriate benchmark.
Executor Framework
โ–ช Introduced in Java 5 (ExecutorService) as a higher level replacement for
working with threads directly.
โ–ช Capable of running asynchronous tasks and allow to manage a pool of
threads rather than working with them directly.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
System.out.println("Hello " + threadName);
});
Executor Framework
Using Callable
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(1);
return 777;
} catch (InterruptedException e) {
throw new IllegalStateException("Future was interrupted", e);
}
});
System.out.println("Is the future done ? : " + future.isDone());
Integer result = future.get();
System.out.println("Is the future done? : " + future.isDone());
System.out.println("Result : " + result);
Executor Framework
Multiple Callables
List<Callable<String>> callables = Arrays.asList(
() -> "Future Task 1",
() -> "Future Task 2",
() -> "Future Task 3");
executor.invokeAll(callables)
.stream()
.map(future -> {
try {
return future.get();
} catch (Exception e) {
throw new IllegalStateException(e);
}
})
.forEach(System.out::println);
Executor Framework
ScheduledExecutorService
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> System.out.println("Scheduling at: " + System.currentTimeMillis());
int initialDelay = 0;
int interval = 1;
executor.scheduleAtFixedRate(task, initialDelay, interval, TimeUnit.SECONDS);
Executor Framework
ScheduledExecutorService
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("Scheduling at : " + System.currentTimeMillis());
} catch (InterruptedException e) {
System.err.println("Runnable task interrupted");
}
};
executor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS);
Executor Framework
Demo
Fork/Join Pool
โ–ช Introduced in Java 7 (Java 8 features use it internally)
โ–ช Recursively split a parallelizable task into smaller tasks and then combine
the results of each subtask to produce the final result.
โ–ช pseudocode:
if (task is no longer divisible or small enough) {
sequentially compute the task
} else {
split task in two sub-tasks
recursively call this method to further split each task
wait for the completion of all subtasks
finally combine the results of each subtask
}
Reference : Java 8 in Action - Lambdas, streams, and functional-style programming
Fork/Join Pool
Demo
CompletableFuture
Future
โ–ช Models an asynchronous computation and provides a reference to its
result that will be available when the computation is completed.
โ–ช Invoking a potentially time-consuming operation inside a Future allows
the caller thread to return immediately and continue doing useful work
instead of getting blocked until the operation finishes.
Future vs CompletableFuture
Reference : Java 8 in Action - Lambdas, streams, and functional-style programming
Limitations with Future
โ–ช Combining two asynchronous computations in one, when theyโ€™re
independent and when the second depends on the result of the first
โ–ช Waiting for the completion of all tasks performed by a set of Futures
โ–ช Waiting for the completion of only the quickest task in a set of Futures
โ–ช Reacting to a Future completion (i.e, being notified when the
completion happens and then having the ability to perform a further
action using the result of the Future, instead of being blocked)
Requirement for CompletableFuture
โ–ช The fork/join framework and parallel streams are valuable tools for
parallelism; they split an operation into multiple sub-operations and
perform those sub-operations in parallel on different cores, CPUs.
โ–ช But donโ€™t want to block the computations and waste precious clock
cycles of your CPU.
CompletableFuture
To demonstrate the CompletableFuture features, will be using a
best-price-finder application that contacts multiple online shops to find the
lowest price for a given product or service. This example is used in the
reference book - Java 8 in Action.
Following high level steps will be used to explain CompletableFuture
โ–ช How to provide an asynchronous API for your consumers
โ–ช How to make your code non-blocking when youโ€™re a consumer of a
synchronous (blocking) API
โ–ช How to reactively process events representing the completion of an
asynchronous operation
CompletableFuture
sequentially querying all the shops
public List<String> findPricesSequential(String product) {
return shops.stream()
.map(shop -> shop.getPrice(product))
.collect(Collectors.toList());
}
CompletableFuture
parallely querying all the shops
public List<String> findPricesParallel(String product) {
return shops.parallelStream()
.map(shop -> shop.getPrice(product))
.collect(Collectors.toList());
}
CompletableFuture
List<CompletableFuture<String>> priceFutures = shops.stream()
.map(shop -> CompletableFuture.supplyAsync( () ->
String.format("%s price is %.2f", shop.getName(), shop.getPrice(product))))
.collect(toList());
priceFutures.stream()
.map(CompletableFuture::join)
.collect(toList());
supplyAsync : accepts a Supplier as argument and returns a CompletableFuture that will be
asynchronously completed with the value obtained by invoking that Supplier.
CompletableFuture
Demo
CompletableFuture
Pipelining asynchronous tasks
Adding another asynchronous task to the pipeline :
โ–ช Suppose that all the shops have agreed to use a centralized discount service.
โ–ช The discount service has an applyDiscount method returning the discounted
price for the product quote given.
CompletableFuture
Using the discount service
public List<String> findPricesSequential(String product) {
return shops.stream()
.map(shop -> shop.getPrice(product))
.map(Quote::parse)
.map(Discount::applyDiscount)
.collect(toList());
}
CompletableFuture
Composing synchronous and asynchronous operations
public Stream<CompletableFuture<String>> findPricesStream(String product) {
return shops.stream()
.map(shop -> CompletableFuture.supplyAsync(() -> shop.getPrice(product)))
.map(future -> future.thenApply(Quote::parse))
.map(future -> future.thenCompose(quote -> CompletableFuture.supplyAsync(() ->
Discount.applyDiscount(quote))));
}
Reference : Java 8 in Action - Lambdas, streams, and functional-style programming
CompletableFuture
Composing synchronous and asynchronous operations
โ–ช supplyAsync (Getting the prices) - query the shop asynchronously. The
result of this first transformation is a CompletableFuture which contains the
String returned by the corresponding shop.
โ–ช thenApply (Parsing the quotes) - convert those Strings into Quotes with a
second transformation. But because this parsing operation isnโ€™t invoking any
remote service (no I/O in general), it can be invoked synchronously.
CompletableFuture
Composing synchronous and asynchronous operations
โ–ช thenCompose (Composing two different futures) - involves contacting the
remote Discount service to apply the appropriate discount percentage to the
non-discounted prices. This is executed remotely and for this reason we
want to perform it asynchronously - by creating another CompletableFuture
using supplyAsync method.
โ–ช thenCompose allows to pipeline two asynchronous operations, passing the
result of the first operation to the second operation when it becomes
available.
CompletableFuture
Composing synchronous and asynchronous operations
Demo
CompletableFuture
Reacting to a CompletableFuture completion
โ–ช thenAccept : specifies how to consume the result produced by the
CompletableFuture when it becomes available and returns a
CompletableFuture<Void>.
CompletableFuture[] futures = findPricesStream(product)
.map(f -> f.thenAccept(s -> System.out.println(s + " (done in " +
((System.nanoTime() - start) / 1_000_000) + " msecs)")))
.toArray(CompletableFuture[]::new);
CompletableFuture.allOf(futures).join();
CompletableFuture
Reacting to a CompletableFuture completion
Demo
CompletableFuture
Using custom executor
โ–ช The parallel stream version performs so well only because it can run 8 tasks
(8 core) in parallel, so itโ€™s able to allocate exactly one thread for each shop.
โ–ช But what happens if you decide to add a 9th shop to the list of shops?
CompletableFuture
Using custom executor
Demo
ConcurrentHashMap Improvements
โ–ช With Java 8, ConcurrentHashMap has been enhanced with a set of
new methods to perform parallel operations effectively on it.
โ–ช forEach(): is capable of iterating over the key-value pairs of the map in
parallel.
โ–ช search(): returns a non-null search result for the current key-value pair
or null if the current iteration doesn't match the desired search criteria
passed as a BiFunction. (variants searchKeys, searchValues)
โ–ช reduce(): accepts two lambda expressions, first function transforms
each key-value pair into a single value of any type. The second function
combines all those transformed values into a single result - like map
and then reduce
ConcurrentHashMap Improvements
โ— Other methods
โ—‹ putIfAbsent
โ—‹ getOrDefault
โ—‹ replaceAll
โ—‹ compute: with two variants computeIfAbsent() and
computeIfPresent()
โ—‹ forEachKey
โ—‹ forEachValue
ConcurrentHashMap Improvements
Demo
References
โ— Java 8 in Action - Lambdas, streams, and functional-style programming by
Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft
โ—‹ Examples - https://github.com/java8/Java8InAction
โ— http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-exam
ples/
โ—‹ Examples - https://github.com/winterbe/java8-tutorial
โ— Examples used in the session : https://github.com/Kishanthan/java8
THANK YOU
wso2.com

More Related Content

What's hot

Webๆณจๅ…ฅ+httpๆผๆดž็ญ‰ๆ่ฟฐ
Webๆณจๅ…ฅ+httpๆผๆดž็ญ‰ๆ่ฟฐWebๆณจๅ…ฅ+httpๆผๆดž็ญ‰ๆ่ฟฐ
Webๆณจๅ…ฅ+httpๆผๆดž็ญ‰ๆ่ฟฐ
fangjiafu
ย 

What's hot (20)

Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
ย 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
ย 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
ย 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
ย 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
ย 
React table tutorial use filter (part 2)
React table tutorial use filter (part 2)React table tutorial use filter (part 2)
React table tutorial use filter (part 2)
ย 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
ย 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
ย 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
ย 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
ย 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
ย 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
ย 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2
ย 
50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes
ย 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
ย 
Proxy deep-dive java-one_20151027_001
Proxy deep-dive java-one_20151027_001Proxy deep-dive java-one_20151027_001
Proxy deep-dive java-one_20151027_001
ย 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
ย 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
ย 
Webๆณจๅ…ฅ+httpๆผๆดž็ญ‰ๆ่ฟฐ
Webๆณจๅ…ฅ+httpๆผๆดž็ญ‰ๆ่ฟฐWebๆณจๅ…ฅ+httpๆผๆดž็ญ‰ๆ่ฟฐ
Webๆณจๅ…ฅ+httpๆผๆดž็ญ‰ๆ่ฟฐ
ย 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
ย 

Similar to What is new in java 8 concurrency

Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
EPAM_Systems_Bulgaria
ย 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
Martin Toshev
ย 
Java 7 & 8
Java 7 & 8Java 7 & 8
Java 7 & 8
Ken Coenen
ย 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Abhijit Gaikwad
ย 

Similar to What is new in java 8 concurrency (20)

Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
ย 
Understanding Reactive Programming
Understanding Reactive ProgrammingUnderstanding Reactive Programming
Understanding Reactive Programming
ย 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
ย 
OSGi ecosystems compared on Apache Karaf - Christian Schneider
OSGi ecosystems compared on Apache Karaf - Christian SchneiderOSGi ecosystems compared on Apache Karaf - Christian Schneider
OSGi ecosystems compared on Apache Karaf - Christian Schneider
ย 
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
ย 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
ย 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
ย 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
ย 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
ย 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
ย 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
ย 
Java 7 & 8
Java 7 & 8Java 7 & 8
Java 7 & 8
ย 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
ย 
Belfast JUG 23-10-2013
Belfast JUG 23-10-2013Belfast JUG 23-10-2013
Belfast JUG 23-10-2013
ย 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
ย 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
ย 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ย 
Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014
ย 
Arquitecturas de microservicios - Medianet Software
Arquitecturas de microservicios   -  Medianet SoftwareArquitecturas de microservicios   -  Medianet Software
Arquitecturas de microservicios - Medianet Software
ย 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
ย 

More from kshanth2101

More from kshanth2101 (6)

Ballerina Tutorial @ SummerSOC 2019
Ballerina Tutorial @ SummerSOC 2019Ballerina Tutorial @ SummerSOC 2019
Ballerina Tutorial @ SummerSOC 2019
ย 
Evolution of Application Development
Evolution of Application DevelopmentEvolution of Application Development
Evolution of Application Development
ย 
WSO2Con Europe 2016 - Extension Points of Carbon Architecture
WSO2Con Europe 2016 - Extension Points of Carbon ArchitectureWSO2Con Europe 2016 - Extension Points of Carbon Architecture
WSO2Con Europe 2016 - Extension Points of Carbon Architecture
ย 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
ย 
Introduction to OSGi - Part-1
Introduction to OSGi - Part-1Introduction to OSGi - Part-1
Introduction to OSGi - Part-1
ย 
Introduction to OSGi - Part-2
Introduction to OSGi - Part-2Introduction to OSGi - Part-2
Introduction to OSGi - Part-2
ย 

Recently uploaded

Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
ย 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
ย 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
ย 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
ย 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
ย 

Recently uploaded (20)

Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
ย 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ย 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
ย 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
ย 
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
ย 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
ย 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
ย 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
ย 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
ย 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
ย 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
ย 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
ย 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
ย 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
ย 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
ย 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
ย 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
ย 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
ย 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
ย 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
ย 

What is new in java 8 concurrency

  • 1. What is new in Java 8 Concurrency T. Kishanthan Technical Lead, WSO2 June 15, 2017
  • 2. Agenda โ— Java 8 - Lambda expressions, Streams โ— Streams vs Parallel Streams โ— Executor Framework โ— Fork/Join Pool โ— CompletableFuture โ— ConcurrentHashMap Improvements 2
  • 3. Java 8 Basics Lambda 3 โ–ช A representation of an anonymous function which is passed around. โ–ช It doesnโ€™t have a name, but has a list of parameters, a body, a return type.
  • 4. Java 8 Basics Lambda 4 Before: Comparator<Apple> byWeight = new Comparator<Apple>() { public int compare(Apple a1, Apple a2) { return a1.getWeight().compareTo(a2.getWeight()); } }; After: Comparator<Apple> byWeight = (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
  • 5. Java 8 Basics Lambda 5 Before: Runnable r2 = new Runnable() { @Override public void run() { System.out.println("Hello Java Colombo!"); } }; After: Runnable r1 = () -> System.out.println("Hello Java Colombo!");
  • 6. Java 8 Basics Streams 6 โ€œA sequence of elements from a source that supports data processing operations.โ€
  • 7. Java 8 Basics Streams 7 โ–ช Source - A data source such as collections, arrays, or I/O resources, where streams consumes the elements. โ–ช Sequence of elements - A stream provides a way to a get sequenced set of values of a specific element type from a source. Collections are about data but streams are about computations that applied on it. โ–ช Data processing operations - Supports common set of operations like functional programming languages to manipulate data, such as filter, map, reduce, find, sort, etc. Operations can be executed either sequentially or in parallel.
  • 8. Java 8 Basics 8 public static List<String> getLowCaloricDishesNamesInJava7(List<Dish> dishes) { List<Dish> lowCaloricDishes = new ArrayList<>(); for (Dish d : dishes) { if (d.getCalories() < 400) { lowCaloricDishes.add(d); } } List<String> lowCaloricDishesName = new ArrayList<>(); Collections.sort(lowCaloricDishes, new Comparator<Dish>() { public int compare(Dish d1, Dish d2) { return Integer.compare(d1.getCalories(), d2.getCalories()); } }); for (Dish d : lowCaloricDishes) { lowCaloricDishesName.add(d.getName()); } return lowCaloricDishesName; }
  • 9. Java 8 Basics 9 public static List<String> getLowCaloricDishesNamesInJava8(List<Dish> dishes) { return dishes.stream() .filter(d -> d.getCalories() < 400) .sorted(comparing(Dish::getCalories)) .map(Dish::getName) .collect(toList()); }
  • 10. Java 8 Basics Chaining stream operations forming a stream pipeline 10 Reference : Java 8 in Action - Lambdas, streams, and functional-style programming
  • 11. Java 8 Basics Chaining stream operations forming a stream pipeline 11 Demo
  • 12. Streams vs Parallel Streams โ–ช Parallel stream splits its data elements into multiple chunks, processing each chunk with a different thread. โ–ช Automatically partition the workload of a given operation on all the cores of your multicore processor and keep all of them busy that idling.
  • 13. Streams vs Parallel Streams โ–ช Sequential version public static long sequentialSum(long n) { return Stream.iterate(1L, i -> i + 1) .limit(n) .reduce(Long::sum) .get(); }
  • 14. Streams vs Parallel Streams โ–ช Parallel version public static long parallelSum(long n) { return Stream.iterate(1L, i -> i + 1) .limit(n) .parallel() .reduce(Long::sum) .get(); }
  • 15. Reference : Java 8 in Action - Lambdas, streams, and functional-style programming
  • 16. Parallel Streams - Performance Demo
  • 17. Parallel Streams - Best Practices โ–ช Automatic boxing and unboxing operations can dramatically hurt performance โ–ช Some operations naturally perform worse on a parallel stream than on a sequential stream - findAny will perform better than findFirst - as no ordering is needed โ–ช For small amount of data, using a parallel stream is not the correct choice (almost) โ–ช Parallel stream isnโ€™t always faster than the corresponding sequential version and can sometimes work in a counterintuitive way - check their performance with an appropriate benchmark.
  • 18. Executor Framework โ–ช Introduced in Java 5 (ExecutorService) as a higher level replacement for working with threads directly. โ–ช Capable of running asynchronous tasks and allow to manage a pool of threads rather than working with them directly. ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -> { System.out.println("Hello " + threadName); });
  • 19. Executor Framework Using Callable ExecutorService executor = Executors.newFixedThreadPool(1); Future<Integer> future = executor.submit(() -> { try { TimeUnit.SECONDS.sleep(1); return 777; } catch (InterruptedException e) { throw new IllegalStateException("Future was interrupted", e); } }); System.out.println("Is the future done ? : " + future.isDone()); Integer result = future.get(); System.out.println("Is the future done? : " + future.isDone()); System.out.println("Result : " + result);
  • 20. Executor Framework Multiple Callables List<Callable<String>> callables = Arrays.asList( () -> "Future Task 1", () -> "Future Task 2", () -> "Future Task 3"); executor.invokeAll(callables) .stream() .map(future -> { try { return future.get(); } catch (Exception e) { throw new IllegalStateException(e); } }) .forEach(System.out::println);
  • 21. Executor Framework ScheduledExecutorService ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); Runnable task = () -> System.out.println("Scheduling at: " + System.currentTimeMillis()); int initialDelay = 0; int interval = 1; executor.scheduleAtFixedRate(task, initialDelay, interval, TimeUnit.SECONDS);
  • 22. Executor Framework ScheduledExecutorService ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); Runnable task = () -> { try { TimeUnit.SECONDS.sleep(2); System.out.println("Scheduling at : " + System.currentTimeMillis()); } catch (InterruptedException e) { System.err.println("Runnable task interrupted"); } }; executor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS);
  • 24. Fork/Join Pool โ–ช Introduced in Java 7 (Java 8 features use it internally) โ–ช Recursively split a parallelizable task into smaller tasks and then combine the results of each subtask to produce the final result. โ–ช pseudocode: if (task is no longer divisible or small enough) { sequentially compute the task } else { split task in two sub-tasks recursively call this method to further split each task wait for the completion of all subtasks finally combine the results of each subtask }
  • 25. Reference : Java 8 in Action - Lambdas, streams, and functional-style programming
  • 27. CompletableFuture Future โ–ช Models an asynchronous computation and provides a reference to its result that will be available when the computation is completed. โ–ช Invoking a potentially time-consuming operation inside a Future allows the caller thread to return immediately and continue doing useful work instead of getting blocked until the operation finishes.
  • 28. Future vs CompletableFuture Reference : Java 8 in Action - Lambdas, streams, and functional-style programming
  • 29. Limitations with Future โ–ช Combining two asynchronous computations in one, when theyโ€™re independent and when the second depends on the result of the first โ–ช Waiting for the completion of all tasks performed by a set of Futures โ–ช Waiting for the completion of only the quickest task in a set of Futures โ–ช Reacting to a Future completion (i.e, being notified when the completion happens and then having the ability to perform a further action using the result of the Future, instead of being blocked)
  • 30. Requirement for CompletableFuture โ–ช The fork/join framework and parallel streams are valuable tools for parallelism; they split an operation into multiple sub-operations and perform those sub-operations in parallel on different cores, CPUs. โ–ช But donโ€™t want to block the computations and waste precious clock cycles of your CPU.
  • 31. CompletableFuture To demonstrate the CompletableFuture features, will be using a best-price-finder application that contacts multiple online shops to find the lowest price for a given product or service. This example is used in the reference book - Java 8 in Action. Following high level steps will be used to explain CompletableFuture โ–ช How to provide an asynchronous API for your consumers โ–ช How to make your code non-blocking when youโ€™re a consumer of a synchronous (blocking) API โ–ช How to reactively process events representing the completion of an asynchronous operation
  • 32. CompletableFuture sequentially querying all the shops public List<String> findPricesSequential(String product) { return shops.stream() .map(shop -> shop.getPrice(product)) .collect(Collectors.toList()); }
  • 33. CompletableFuture parallely querying all the shops public List<String> findPricesParallel(String product) { return shops.parallelStream() .map(shop -> shop.getPrice(product)) .collect(Collectors.toList()); }
  • 34. CompletableFuture List<CompletableFuture<String>> priceFutures = shops.stream() .map(shop -> CompletableFuture.supplyAsync( () -> String.format("%s price is %.2f", shop.getName(), shop.getPrice(product)))) .collect(toList()); priceFutures.stream() .map(CompletableFuture::join) .collect(toList()); supplyAsync : accepts a Supplier as argument and returns a CompletableFuture that will be asynchronously completed with the value obtained by invoking that Supplier.
  • 36. CompletableFuture Pipelining asynchronous tasks Adding another asynchronous task to the pipeline : โ–ช Suppose that all the shops have agreed to use a centralized discount service. โ–ช The discount service has an applyDiscount method returning the discounted price for the product quote given.
  • 37. CompletableFuture Using the discount service public List<String> findPricesSequential(String product) { return shops.stream() .map(shop -> shop.getPrice(product)) .map(Quote::parse) .map(Discount::applyDiscount) .collect(toList()); }
  • 38. CompletableFuture Composing synchronous and asynchronous operations public Stream<CompletableFuture<String>> findPricesStream(String product) { return shops.stream() .map(shop -> CompletableFuture.supplyAsync(() -> shop.getPrice(product))) .map(future -> future.thenApply(Quote::parse)) .map(future -> future.thenCompose(quote -> CompletableFuture.supplyAsync(() -> Discount.applyDiscount(quote)))); }
  • 39. Reference : Java 8 in Action - Lambdas, streams, and functional-style programming
  • 40. CompletableFuture Composing synchronous and asynchronous operations โ–ช supplyAsync (Getting the prices) - query the shop asynchronously. The result of this first transformation is a CompletableFuture which contains the String returned by the corresponding shop. โ–ช thenApply (Parsing the quotes) - convert those Strings into Quotes with a second transformation. But because this parsing operation isnโ€™t invoking any remote service (no I/O in general), it can be invoked synchronously.
  • 41. CompletableFuture Composing synchronous and asynchronous operations โ–ช thenCompose (Composing two different futures) - involves contacting the remote Discount service to apply the appropriate discount percentage to the non-discounted prices. This is executed remotely and for this reason we want to perform it asynchronously - by creating another CompletableFuture using supplyAsync method. โ–ช thenCompose allows to pipeline two asynchronous operations, passing the result of the first operation to the second operation when it becomes available.
  • 42. CompletableFuture Composing synchronous and asynchronous operations Demo
  • 43. CompletableFuture Reacting to a CompletableFuture completion โ–ช thenAccept : specifies how to consume the result produced by the CompletableFuture when it becomes available and returns a CompletableFuture<Void>. CompletableFuture[] futures = findPricesStream(product) .map(f -> f.thenAccept(s -> System.out.println(s + " (done in " + ((System.nanoTime() - start) / 1_000_000) + " msecs)"))) .toArray(CompletableFuture[]::new); CompletableFuture.allOf(futures).join();
  • 44. CompletableFuture Reacting to a CompletableFuture completion Demo
  • 45. CompletableFuture Using custom executor โ–ช The parallel stream version performs so well only because it can run 8 tasks (8 core) in parallel, so itโ€™s able to allocate exactly one thread for each shop. โ–ช But what happens if you decide to add a 9th shop to the list of shops?
  • 47. ConcurrentHashMap Improvements โ–ช With Java 8, ConcurrentHashMap has been enhanced with a set of new methods to perform parallel operations effectively on it. โ–ช forEach(): is capable of iterating over the key-value pairs of the map in parallel. โ–ช search(): returns a non-null search result for the current key-value pair or null if the current iteration doesn't match the desired search criteria passed as a BiFunction. (variants searchKeys, searchValues) โ–ช reduce(): accepts two lambda expressions, first function transforms each key-value pair into a single value of any type. The second function combines all those transformed values into a single result - like map and then reduce
  • 48. ConcurrentHashMap Improvements โ— Other methods โ—‹ putIfAbsent โ—‹ getOrDefault โ—‹ replaceAll โ—‹ compute: with two variants computeIfAbsent() and computeIfPresent() โ—‹ forEachKey โ—‹ forEachValue
  • 50. References โ— Java 8 in Action - Lambdas, streams, and functional-style programming by Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft โ—‹ Examples - https://github.com/java8/Java8InAction โ— http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-exam ples/ โ—‹ Examples - https://github.com/winterbe/java8-tutorial โ— Examples used in the session : https://github.com/Kishanthan/java8