SlideShare a Scribd company logo
Think Async
in Java 8
2
Asynchronous
Asynchronous
Multi threading
Way to Think in Async
3
synchronous
Synchronous
4
Single-Threaded
Synchronous
5
Multi-Threaded
6
Asynchronous
Asynchronous
7
Single-Threaded
Asynchronous
8
Multi-Threaded
Asynchronous
✗ It can be really faster
✗ Its non-blocking
✗ No gap between tasks
9
Asynchronous vs Multi-thread
✗ Synchronous Single Threaded
✗ Synchronous Multi-Threaded
✗ Asynchronous Single Threaded
✗ Asynchronous Multi-Threaded
10
11
Asynchronous in Java
Runnable
Java 1
Do not have
the option
to notify in
case of any
error
12
Asynchronous in Java
Runnable Callable
Java 1 Java 5
Have option
to notify in
case of any
error
13
Asynchronous in Java
Runnable Callable
Executer
Service
Java 1 Java 5 Java 5
Future
Java 5
Asynchronous use case
14
Callable<String> task = () --‐>
"select user from User"
executorService.submit
(task)
Future<String>
Future
15
main Thread 1
Submit()
get()
Result ready
Future
16
main Thread 1
Submit()
get()
Result ready
Blockingthemain
thread
17
Future
main Thread 1
Submit()
get()
Result ready
Don’t have
the ability
to attach a
callback
function
18
Asynchronous use case
main Thread 1 Thread 2 Thread 3
task1
task2
task3
task4
19
Asynchronous use case
main Thread 1 Thread 2 Thread 3
task1
task2
task3
task4
Multiple
Futures
cannot be
chained
together
20
Asynchronous use case
Can not
combine
multiple
Futures
together
“We have to make
callback”
21
22
Callbacks
Main
Thread Thread pool
Event
Timer
File I/O
User code
Async API
Calls
Callback method
23
Callbacks
public void processAsync( ExecutorService executor, Supplier supplier, Consumer onSuccess )
{
executor.submit(() -> {
List lines = supplier.get();
onSuccess.accept(lines);
});
}
Consumer onSuccess
onSuccess.accept(lines);
24
Callbacks
public void processAsync( ExecutorService executor, Supplier supplier, Consumer onSuccess ,
Consumer onFail ) {
executor.submit(() -> {
try {
List lines = supplier.get();
onSuccess.accept(lines);
catch(Exception e) {
onFail.accept(e);
}
});
}
Consumer onSuccess
Consumer onFail
onSuccess.accept(lines);
onFail.accept(e);
Drawbacks of Callbacks
✗ Do not scale well for even moderately complex
asynchronous code
✗ Multiple callback function hard to read, easy to
break, and hard to debug
25
“How to achieve
asynchronicity in java”
26
We have new tools in Java 8 to
handle this precise case It brings
new solutions to chain tasks
27
Asynchronous in Java 8
Handle both asynchronous and
multithreaded programming
28
Asynchronous in Java 8
29
CompletableFuture Intro
Future<T> CompletionStage<T>
CompletableFuture<?>
30
CompletableFuture Intro
Future<T>
Completion
Stage<T>
Completable
Future<?>
✗ task may be running
✗ task may have
Complete normally
✗ task may have
complete
exceptionally
It has a state:
Async java8
32
Creating Method
✗ new
✗ supplyAsync()
✗ runAsync()
33
Creating a CompletableFuture
CompletableFuture<String> cf = new CompletableFuture<>();
String result = cf.get();
String result = cf. complete(“ Killed !! ”);
`
CompletableFuture
With no-arg
constructor
Blocks until the
Future is complete
Complete a Future
manually
34
Running asynchronous
ExecutorService es = Executors.newCachedThreadPool();
es.execute (new Runnable() {
public void run() {
System.out.print("Hello Java“);
}
});
CompletableFuture<Void> cf = CompletableFuture.runAsync (
() -> {
System.out.print("Hello Java“);
});
Java 7
Java 8
es.execute
CompletableFuture.runAsync
35
Running asynchronous
ExecutorService es = Executors.newCachedThreadPool();
Future<String> future = es.submit(new Callable<String>() {
public String call() throws Exception {
return "Hello Java";
}
});
CompletableFuture<String> cf =
CompletableFuture.supplyAsync(() -> {
return "Hello Java";
});
Java 7
Java 8
es.submit
CompletableFuture.supplyAsync
36
Create Method
✗ CompletableFuture() cf = new CompletableFuture();
✗ CompletableFuture<U> :: supplyAsync( Supplier<U>supplier )
✗ CompletableFuture<U> :: runAsync ( Runnable runnable )
Supplier<U>supplier
Runnable runnable
37
Create Method
✗ CompletableFuture<U> :: supplyAsync (Supplier<U>supplier)
✗ CompletableFuture<U> :: runAsync (Runnable runnable)
supplyAsync
runAsync
ForkJoinPool :: commonPool()
38
Create Method
✗ CompletableFuture<U> :: supplyAsync ( Supplier<U>supplier
, Executor executor )
✗ CompletableFuture<U> :: runAsync(Runnable runnable ,
,Executor executor )
Executor executor
Executor executor
39
Attach Callback Method
✗ thenApply()
✗ thenAccept()
✗ thenRun()
40
thenApply
CompletableFuture<String> cf =
CompletableFuture.supplyAsync(() -> {
return "Hello ";
}).thenApply ( s -> {
return s + "World ";
}).thenApply (s -> {
return "First " + s + " Programe!!";
});
thenApply
thenApply
cf.get()  “First Hello World Programe”
41
thenAccept
CompletableFuture.supplyAsync(() -> {
return "Hello ";
}).thenApply ( s -> {
return s + "World ";
}).thenApply (s -> {
return "First " + s + " Programe!!";
}).thenAccept (result -> {
System.out.print(result);
});
thenAccept
cf.get()  “First Hello World Programe”
42
thenRun
CompletableFuture.supplyAsync(() -> {
return "Hello ";
}).thenApply ( s -> {
return s + "World ";
}).thenRun (() -> {
//TODO: some other work
});
thenRun
43
Async Callback
CompletableFuture.supplyAsync(() -> {
return "Hello ";
}).thenApply ( s -> {
return s + "World ";
});
CompletableFuture.supplyAsync(() -> {
return "Hello ";
}).thenApplyAsync ( s -> {
return s + "World ";
});
thenApply
Executed in the same thread
where the supplyAsync()
task is executed
thenApplyAsync
Executed in a different
thread from
ForkJoinPool.commonPool()
44
Combining together
✗ thenCompose()
✗ thenCombine()
✗ allOf()
✗ anyOf()
45
thenCompose
CompletableFuture<User> cf =
CompletableFuture.supplyAsync((Long id) -> {
return getUserInfo(id);
});
CompletableFuture<User>
I wanted to call the method
inside the user object and
also need to chain..?
46
thenCompose
CompletableFuture<String> cf =
CompletableFuture.supplyAsync((Long id) -> {
return getUserInfo(id);
}). thenCompose (user -> {
return user.getName();
});
thenCompose
Monads
thenApply
thenCompose
47
thenCombine
CompletableFuture<String> cf1
= CompletableFuture.supplyAsync(() -> "Hello“
CompletableFuture<String> cf2
= CompletableFuture.supplyAsync(() -> “World“
CompletableFuture<String> result
= cf1.thenCombine (cf2, (s1, s2) -> { s1 + s2 } );thenCombine ( s1, s2 ) -> { s1 + s2 }
Callback method is
invoked both task is
completed
48
allOf and anyOf
✗ CompletableFuture <Void> :: allOf ( CompletableFuture<?>... Cfs )
✗ CompletableFuture <Object> :: anyOf ( CompletableFuture<?>... cfs )
CompletableFuture<?>... cfs
CompletableFuture<?>... cfs
<Void>
<Object>
49
Exception Handling
✗ exceptionally()
✗ handle()
50
exceptionally
CompletableFuture.supplyAsync(() -> {
//TODO: some work here
}). exceptionally ( ex -> {
System.out.print(“exception occurred in future:” + ex);
//TODO: some other work
});
exceptionally ex
51
handle
CompletableFuture.supplyAsync(() -> {
//TODO: some work here
}). handle (( res, ex ) -> {
//TODO: some other work
});
handle res, ex
It is called whether or not
an exception occurs
52
CompletableFuture for Async
When we program asynchronously we usually think in terms of workflows,
events and tasks
✗ Do this then that
✗ Do this and/or that
✗ Do this on failure
Chaining
Joining
Recovering
This is your
presentation
title

More Related Content

KEY
Don’t block the event loop!
PPTX
Coroutines talk ppt
PDF
aiohttp intro
PDF
What Is Async, How Does It Work, And When Should I Use It?
PPTX
Introduction to Vert.x
PPTX
Node child process
KEY
Streams are Awesome - (Node.js) TimesOpen Sep 2012
PPT
JS everywhere 2011
Don’t block the event loop!
Coroutines talk ppt
aiohttp intro
What Is Async, How Does It Work, And When Should I Use It?
Introduction to Vert.x
Node child process
Streams are Awesome - (Node.js) TimesOpen Sep 2012
JS everywhere 2011

What's hot (20)

PDF
Cooking pies with Celery
PPTX
How NOT to write in Node.js
PPTX
Introduction to Node.js
PPTX
Gevent rabbit rpc
PDF
Asynchronous programming done right - Node.js
PDF
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
PDF
asyncio community, one year later
PDF
Test driven infrastructure
PDF
Node, can you even in CPU intensive operations?
PDF
DevOps(2) : Vagrant - (MOSG)
PDF
HTTPBuilder NG: Back From The Dead
PPTX
Javascript asynchronous
PDF
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
PDF
Ansible 2.0
PDF
Instruction: dev environment
ODP
Владимир Перепелица "Модули"
PDF
Preparation study of_docker - (MOSG)
PDF
"Swoole: double troubles in c", Alexandr Vronskiy
PDF
DevOps(3) : Ansible - (MOSG)
Cooking pies with Celery
How NOT to write in Node.js
Introduction to Node.js
Gevent rabbit rpc
Asynchronous programming done right - Node.js
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
asyncio community, one year later
Test driven infrastructure
Node, can you even in CPU intensive operations?
DevOps(2) : Vagrant - (MOSG)
HTTPBuilder NG: Back From The Dead
Javascript asynchronous
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Ansible 2.0
Instruction: dev environment
Владимир Перепелица "Модули"
Preparation study of_docker - (MOSG)
"Swoole: double troubles in c", Alexandr Vronskiy
DevOps(3) : Ansible - (MOSG)
Ad

Similar to Async java8 (20)

PDF
Completable future
ODP
Concurrent Programming in Java
PDF
Asynchronous API in Java8, how to use CompletableFuture
PDF
Leverage CompletableFutures to handle async queries. DevNexus 2022
PDF
The Future of Futures - A Talk About Java 8 CompletableFutures
PDF
Leveraging Completable Futures to handle your query results Asynchrhonously
PPTX
parallel-asynchronous-programming-java.pptx
PDF
Asynchronous programming with Java & Spring
PPTX
Completable Future java 8 Features with example
PDF
Programming Sideways: Asynchronous Techniques for Android
PDF
What is new in java 8 concurrency
PPTX
Back to the [Completable] Future
PPTX
Java 8 concurrency abstractions
PDF
Java concurrency model - The Future Task
ODP
CompletableFuture
PPTX
Introduction to ParSeq: to make asynchronous java easier
PDF
A first look into the Project Loom in Java
PPTX
Think Async in Java 8
ODP
Java Concurrency, Memory Model, and Trends
PDF
Loom Virtual Threads in the JDK 19
Completable future
Concurrent Programming in Java
Asynchronous API in Java8, how to use CompletableFuture
Leverage CompletableFutures to handle async queries. DevNexus 2022
The Future of Futures - A Talk About Java 8 CompletableFutures
Leveraging Completable Futures to handle your query results Asynchrhonously
parallel-asynchronous-programming-java.pptx
Asynchronous programming with Java & Spring
Completable Future java 8 Features with example
Programming Sideways: Asynchronous Techniques for Android
What is new in java 8 concurrency
Back to the [Completable] Future
Java 8 concurrency abstractions
Java concurrency model - The Future Task
CompletableFuture
Introduction to ParSeq: to make asynchronous java easier
A first look into the Project Loom in Java
Think Async in Java 8
Java Concurrency, Memory Model, and Trends
Loom Virtual Threads in the JDK 19
Ad

Recently uploaded (20)

PPTX
CHAPTER 2 - PM Management and IT Context
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Nekopoi APK 2025 free lastest update
PDF
PTS Company Brochure 2025 (1).pdf.......
PPT
Introduction Database Management System for Course Database
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
System and Network Administration Chapter 2
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Designing Intelligence for the Shop Floor.pdf
PDF
medical staffing services at VALiNTRY
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
ai tools demonstartion for schools and inter college
CHAPTER 2 - PM Management and IT Context
How to Migrate SBCGlobal Email to Yahoo Easily
Operating system designcfffgfgggggggvggggggggg
wealthsignaloriginal-com-DS-text-... (1).pdf
Nekopoi APK 2025 free lastest update
PTS Company Brochure 2025 (1).pdf.......
Introduction Database Management System for Course Database
2025 Textile ERP Trends: SAP, Odoo & Oracle
How to Choose the Right IT Partner for Your Business in Malaysia
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
System and Network Administration Chapter 2
Design an Analysis of Algorithms I-SECS-1021-03
Which alternative to Crystal Reports is best for small or large businesses.pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Designing Intelligence for the Shop Floor.pdf
medical staffing services at VALiNTRY
Odoo Companies in India – Driving Business Transformation.pdf
Reimagine Home Health with the Power of Agentic AI​
ai tools demonstartion for schools and inter college

Async java8

Editor's Notes

  • #19: The Future interface was added in Java 5 to serve as a result of an asynchronous computation, but it did not have any methods to combine these computations or handle possible errors.
  • #20: The Future interface was added in Java 5 to serve as a result of an asynchronous computation, but it did not have any methods to combine these computations or handle possible errors.