Parallel Asynchronous Programming Java
Parallel Asynchronous Programming Java
&
Asynchronous Programming
In
Modern Java
Dilip Sundarraj
About Me
• Dilip
• Developers who has the need to write code that executes faster
• Developers who has the need to write code that executes in Parallel
• In Software Programming:
Lamdas
Data Parallelism Streams API
https://en.wikipedia.org/wiki/Java_version_history
Concurrency
vs
Parallelism
Concurrency
• Concurrency is a concept where two or more task can run simultaneously
• Concurrent Collections
System.out.println("Result is : " + result);
}
• Conditional Objects and More }
Hello World
Parallelism Fork/Join (Parallelism)
Task
• Parallelism is a concept in which
tasks are literally going to run in
1 fork
parallel
SubTask1 SubTask2
fork fork
• Parallelism involves these steps:
join join
3
• Whole process is also called Fork/
Join
join
Parallelism Example Fork/Join (Parallelism)
[Bob, Jamie, Jill, Rick] -> [BOB, JAMIE, JILL, RICK] 1 fork
[Bob,Jamie] [Jill,Rick]
fork fork
Bob Jamie Jill Rick Process Sequentially Process Sequentially Process Sequentially Process Sequentially
}
}
Concurrency vs Parallelism
ProductInfo
size, color, price
Service
ProductId
Product Review
No of reviews,
Service Overall rating
Product
Threads
Threads API
• Threads API got introduced in Java1
• Runnable, Thread
• Low level
• I/O task
ExecutorService
WorkQueue
ThreadPool
T1 T2
CompletionQueue
T3 T4
Working Of ExecutorService
ExecutorService
WorkQueue ThreadPool
Client Task
T1 T2
Future
CompletionQueue
T3 T4
Result
Limitations of ExecutorService
• Designed to Block the Thread
conquer approach
[BOB, [JILL, RICK] join
JAMIE] join
3
ForkJoin Pool
Double Ended Work Queue(deck)
Task
WorkStealing
Client ForkJoinTask
Task T2
Worker Threads
Result
Shared Work Queue
Task T3
Task T4
ForkJoin Task
Fork/Join (Parallelism)
fork
• Type of tasks to submit to ForkJoin Pool
[Bob,Jamie] [Jill,Rick]
fork fork
• ForkJoinTask
value
Task Process Sequentially Process Sequentially Process Sequentially Process Sequentially
Input Output
Intermediate
Terminal
1
3
] Pipeline
ParallelStreams
Stream
Parallel Stream
Parallel Streams - UseCase
Input Output
• Unit Testing allows the developer or the app team to make enhancements to the
Sequential
parallel()
Parallel
When to use sequential() and parallel() ?
Used these functions when I would like to evaluate between sequential() and
parallel()
Overview of the
Retail
Checkout
Service
Checkout Service(BackEnd)
UP
• Execute
• Data chunks are applied to the Stream Pipeline and the Intermediate operations executed in a Common ForkJoin
Pool
• Combine
• collect(toList())
parallelStream() - How it works ?
parallelStreams()
cartItemsList CheckoutService
cartItemsList combine
Comparing
ArrayList vs LinkedList
ParallelStreams
Performance
Spliterator in ParallelStreams
[ 1, 2, 3, 4 ] -> [2, 4, 6, 8]
Value * 2
Summary - Spliterator in ParallelStreams
• Type of Collection
• Example : ArrayList
• Example : Set
• Feature rich and used for many different • Reduce the computation into a single value
use cases
• Sum, Multiplication
• Example
• Example
• collect(toList()), collect(toSet())
• collect(summingDouble(Double::doubleV
alue)); • Multiply -> reduce(1.0, (x , y)->x * y)
How reduce() works ?
[ 1 ,2 ,3 ,4 ]
0+1 => 1
3+3 => 6
6+4 => 10
The reduce( ) function performs an immutable computation throughout in each and every step.
How reduce() with ParallelStream works ?
Sum of N numbers
1
[ 1 ,2 ,3 ,4 ] [ 5 ,6 ,7 ,8 ]
Split Split Split Split
0 0 0 0
36 [ 1 ,2 ] [ 3 ,4 ] [ 5 ,6 ] [ 7 ,8 ]
1 Spliterator
3 7 11 15
reduce()
reduce()
2 ForkJoinPool
3 10 26
reduce() reduce()
3 Reduce
36
Want to learn more ?
Collect() & Reduce()
Hands-On
Identity in reduce()
Identity in reduce()
• Addition: Identity = 0
• 0 + 1 => 1
• 0 + 20 => 20
• Multiplication : Identity = 1
• 1 * 1 => 1
cartItemsList CheckoutService
Split
Split 1 cartItemsSplit cartItemsSplit
Split Split
Execute 2
Process Sequentially Process Sequentially Process Sequentially Process Sequentially
Common ForkJoinPool
cartItemsList combine
Common ForkJoin Pool
T1
Task
parallelStreams() T2
Worker Threads
Result
Shared Work Queue
T3
• ParallelStreams
• CompletableFuture
• parallelStreams()
• Yes
Modifying
Default parallelism
in
Parallel Streams
Modifying Default parallelism
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "100");
OR
-Djava.util.concurrent.ForkJoinPool.common.parallelism=100
Parallel Streams - Summary
Parallel Streams - When to use them ?
Parallel Streams - When to use them ?
• Parallel Streams
• Split
• Execute
• Combine
Parallel Streams - When to use them ?
• Lots of data
• Parallel Streams
• Split
• Execute
• Combine
• Introduced in Java 8
1
• Fundamentally Asynchronous
• Resilient:
• Elastic:
3 2
• Asynchronous Computations normally run in a pool of
threads
• Factory Methods
• Exception Methods
• FactoryMethod
• CompletionStage Method
computation
Interface
• Returns
CompletableFuture<Void>
• Returns CompletableFuture<T>
CompletableFuture
]
1
2
3 Pipeline
Unit Testing
CompletableFuture
Combing independent
Async Tasks
using
“thenCombine"
thenCombine()
• This is a Completion Stage Method
Service1
Service2
• CompletionStage , BiFunction
• Returns a CompletableFuture
thenCompose
thenCompose()
• Returns CompletableFuture<T>
Product Service
ProductInfo
Service
ProductId
Product Review
Service
Product
Combining
Streams
&
CompletableFuture
Product Service with Inventory
ProductInfo
Service
ProductId
Product
Review
Service
Exception
Handling
In
CompletableFuture
Exception Handling in Java
• Exception Handling in Java is available since the inception of Java
]
Exception Handling in CompletableFuture
• CompletableFuture is a functional style API
Exception Handling in CompletableFuture
try/catch
Exception Handling in CompletableFuture
• handle()
Success Path
handle handle
Failure Path
handle handle
Exception Handling using exceptionally()
Success Path
Failure Path
exceptionally exceptionally
whenHandle()
whenHandle()
• Catches the Exception but does not recover from the exception
Exception Handling using whenComplete()
Success Path
whenComplete whenComplete
Failure Path
whenComplete whenComplete
Product Service with Inventory
!
ProductInfo
Service
ProductId
Product
Review
Service
CompletableFuture
Default ThreadPool
CompletableFuture - ThreadPool
• By default, CompletableFuture uses the Common ForkJoinPool
T1
Task
completableFuture() T2
Worker Threads
Result
Shared Work Queue
T3
T4
Watch “Internals of Common ForkJoin Pool” Lecture
CompletableFuture
&
User Defined ThreadPool
using
ExecutorService
Why use a different ThreadPool ?
• ParallelStreams
• CompletableFuture
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Threads
In
CompletableFuture
Async()
Overloaded Functions
In
CompletableFuture
Async Overloaded Functions
• thenAccept()
Async() Overloaded Functions
Regular Functions Async() overloaded Functions
• thenCombine()
• thenCombineAsync()
• thenApply()
• thenApplyAsync()
• thenCompose()
• thenComposeAsync()
• thenAccept() • thenAcceptAsync()
Async() Overloaded Functions
• Use this when you have blocking operations in your Completablefuture pipeline
Introduction to
Spring WebClient
and
Overview of the GitHub Jobs API
About this section
• Spring WebClient is a rest client library that’s got released as part of Spring 5
Service 1
Client Service 2
Service 2
anyOf()
anyOf() - Dealing with Multiple CompletableFutures
• Use anyOf() when you are dealing with retrieving data from multiple Data Sources
DB
SOAP Service
TimeOuts
In
CompletableFuture
Timeouts in CompletableFuture
• orTimeout() in CompletableFutureAPI