SlideShare a Scribd company logo
1 of 53
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:
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

What's hot

Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Tom Croucher
 
Владимир Перепелица "Модули"
Владимир Перепелица "Модули"Владимир Перепелица "Модули"
Владимир Перепелица "Модули"
Media Gorod
 

What's hot (20)

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

Similar to Async java8

Similar to Async java8 (20)

Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
BUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIOBUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIO
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
play framework async with scala
play framework async with scalaplay framework async with scala
play framework async with scala
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
 
Dallas Scala Meetup
Dallas Scala MeetupDallas Scala Meetup
Dallas Scala Meetup
 
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdfITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results Asynchrhonously
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 

Recently uploaded

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 

Async java8

Editor's Notes

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