SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
Completable Future
Srinivasan Raghavan
Senior Member of Technical Staff
Java Platform Group
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Program Agenda
java.util.Future Introduction
Cloud Services Design and the fight for Performance
CompletableFuture and power of parallelism
Building powerful libraries with Completable Future
1
2
3
4
4
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
java.util.Future Introduction
• Before jdk1.5 , no java.util.concurrent.*, only threads ,synchronized primitives
• W ite o e , u a ywhe e ? – g eat su ess , But u it a illio ti es , wo k the sa e ? ig uestio
• In came java.util.concurrent.* with executor service and future tasks and many other concurrency constructs
• A java.util.Future is a construct which holds a result available at a later time
• Future is asynchronous , but its not non-blocking
5
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
The Executor Service and Future Task
• Executors contains pool of threads which accepts tasks and supplies to the Future
• When a task is submitted to the executor it returns a future and future.get() would block the computation until it
ends
6
ExecutorService executorService =
Executors.newFixedThreadPool(20);
Future<Integer> future =
executorService.submit(new Callable<Integer>()
{
@Override
public Integer call() throws Exception {
return 42;
}
});
System.out.println(future.get());
executorService.shutdown();
User Executor
Task (Callable)
Future
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
What can be done ?
• Future can allow computation in the background so improving performance
• Future.get() would block the thread and wait till the computation is complete
and get the result
• Can get an exception if there is a failure
• future.cancel() cancels the computation
• future.isDone() checks the computation is complete
• A d that’s it /////
7
ExecutorService executorService =
Executors.newFixedThreadPool(20);
Future<Integer> future =
executorService.submit(new Callable<Integer>()
{
@Override
public Integer call() throws Exception {
//Some complex work
return 42;
}
});
System.out.println(future.get());
executorService.shutdown();
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Distributed Cloud Services Design and the
fight for Performance
8
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
A Typical distributed cloud service
9
Get data from service
provider 1
Get data from service
provider 3
Get data from service
provider 2
Combine Data
Response(result)
Request(userData,reuestParams)
Processing for analytics Process data for the
user
Generate
recommendation
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Performance Bottlenecks and impacts
• Java.util.Future can help in parallelism
• But it cannot help with pipeline the tasks and managing the thread pool for you
• Future does not supports call backs and chaining of operations
• Building libraries with future can be complictaed
• Performing in a serial way can impact the latency big time
• It can destroy all benefits of having distributed services
• No amount of horizontal and vertical scaling can help
• Without dynamic services offerings business can be affected
10
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
CompletableFuture and power of parallelism
11
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
What is Completable future ?
• Its new addition to java 8
• Asynchronous, allows registering asyc callbacks just like java scripts, event-driven programming model
• Support for depending functions to be triggered on completion
• Each stage can be executed with different executor pool
• Also comes with a built in thread pool for executing tasks
• Built in lambda support ,super flexible and scalable api
12
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Basics
13
CompletableFuture<String> future =
CompletableFuture.supplyAsync(new Supplier<String>()
{
@Override
public String get() {
// ...long running...
return "42";
}
}, executor1);
future.get();
//Come on ... we are in JDK 8 !!!
CompletableFuture<String> future =
CompletableFuture
.supplyAsync(() -> "42",executor1);
future.get();
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Lambdas , Crash Recap
14
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Lambdas
• Function definition that is not bound to an identifier
15
/**
*
* This is a piece of code that illustrate how lambdas work in
Java 8
*
* Given an example
*
* f(x) = 2x+5;
*
* given x= 2 ; f(x) = 9 ;
*
* z(x)= f(g(x)) where g(x) =3x+5
*
* z(x) = 2(3x+5) +5 = 6x+15 12+15 = 27
* *
*/
public class LambdaUnderStanding2 {
@FunctionalInterface
static interface Funct {
int apply(int x);
default Funct compose(Funct before) {
return (x) -> apply(before.apply(x));
}
}
public static void main(String[] args) {
Funct annoymous = new Funct() {
@Override
public int apply(int x) {
return 2 * x + 5;;
}
};
Funct funct = (x) -> 2 * x + 5;
System.out.println(funct.apply(2));
Funct composed = funct.compose((x) -> 3 * x + 5);
System.out.println(composed.apply(2));
}
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Java 8 Functional Interface
16
Predicate<Integer> test = (x) -> x> 10;
Function<Integer, Integer> function = (x) -> 3 * x + 5;
Consumer<Integer> print = (x) -> System.out.println(x);
BiFunction<Integer, Integer, Integer> biFunction = (x, y) -> 3 * x + 4* y + 2;
Supplier<Integer> supplier = () -> Integer.MAX_VALUE;
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
thenApply() -transformations
17
/**
* Classic call back present in javascript or scala .
* theApply is like run this function when the result
*arrives from previous stages
*/
final CompletableFuture<Integer> future1 =
CompletableFuture
.supplyAsync(() -> "42", executor1).thenApply(
(x) -> Integer.parseInt(x));
/**
* thenApply is trasformative changing
CompletableFuture<Integer> to
* CompletableFuture<Double>
*/
CompletableFuture<Double> future2 = CompletableFuture
.supplyAsync(() -> "42", executor1)
.thenApply((x) -> Integer.parseInt(x))
.thenApply(r -> r * r * Math.PI);
/**
* U can supply a differnt executor pool for
thenApply
*/
CompletableFuture<Double> future = CompletableFuture
.supplyAsync(() -> "42", executor1)
.thenApplyAsync((x) -> Integer.parseInt(x),
executor2)
.thenApplyAsync(r -> r * r * Math.PI, executor2);
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
thenCombine() , whenComplete() –completion
18
final CompletableFuture<Integer> future = CompletableFuture
.supplyAsync(() -> "32", executor1).thenApply(
(x) -> Integer.parseInt(x));
CompletableFuture.supplyAsync(() -> "42", executor2)
.thenApply((x) -> Integer.parseInt(x))
.thenCombine(future, (x, y) -> x + y)
.thenAccept((result) -> System.out.println(result));
/**
* When complete is final stage where it can check
the execpetions
* propagated and pass results through it
*/
final CompletableFuture<Integer> future =
CompletableFuture
.supplyAsync(() -> "42", executor1)
.thenApply((x) -> Integer.parseInt(x))
.whenComplete(
(x, throwable) -> {
if (throwable != null) {
Logger.getAnonymousLogger().log(Level.SEVERE,
"Logging" + throwable);
} else {
Logger.getAnonymousLogger().log(Level.FINE,
" Passed " + x);
}
});
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
thenCombine() allOf() - combining futures
19
/**
* Combining two dependent futures
*/
final CompletableFuture<Integer> future =
CompletableFuture
.supplyAsync(() -> "32", executor1).thenApply(
(x) -> Integer.parseInt(x));
CompletableFuture.supplyAsync(() -> "42", executor2)
.thenApply((x) -> Integer.parseInt(x))
.thenCombine(future, (x, y) -> x + y)
.thenAccept((result) -> System.out.println(result));
/**
* Combining n futures unrelated
*/
CompletableFuture<Void> future2 = CompletableFuture
.supplyAsync(() -> "42", executor1)
.thenApplyAsync((x) -> Integer.parseInt(x),
executor2)
.thenAcceptAsync(
(x) -> Logger.getAnonymousLogger().log(Level.FINE,
"Logging" + x), executor2);
CompletableFuture<Void> future1 = CompletableFuture
.supplyAsync(() -> “ ", executor1)
.thenApplyAsync((x) -> Integer.parseInt(x),
executor2)
.thenAcceptAsync(
(x) -> Logger.getAnonymousLogger().log(Level.FINE,
"Logging" + x), executor2);
CompletableFuture.allOf(future1,future2).join();
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Building powerful libraries with Completable
Future
20
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Building powerful libraries with completable futures
• Building scalable service orchestrator
• Building dynamic http client framework
• Improve parallelism in existing services with are done serial
• Building libraries tuned for vertical scalability
21
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
References
• https://docs.oracle.com/javase/tutorial/
• https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Completa
bleFuture.html
• http://cs.oswego.edu/mailman/listinfo/concurrency-interest
• https://github.com/srinivasanraghavan/functional
22
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Questions ?
23
Completable future

Contenu connexe

Tendances

Hello Armeria, Bye Spring
Hello Armeria, Bye SpringHello Armeria, Bye Spring
Hello Armeria, Bye SpringGihwan Kim
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6Rob Eisenberg
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use casesFabio Biondi
 
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...Edureka!
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJosé Paumard
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8Simon Ritter
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 

Tendances (20)

Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Angular Observables & RxJS Introduction
Angular Observables & RxJS IntroductionAngular Observables & RxJS Introduction
Angular Observables & RxJS Introduction
 
Hello Armeria, Bye Spring
Hello Armeria, Bye SpringHello Armeria, Bye Spring
Hello Armeria, Bye Spring
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 

En vedette

Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
 
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 CompletableFuturesHaim Yadid
 
CompletableFuture
CompletableFutureCompletableFuture
CompletableFuturekoji lin
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8Garth Gilmour
 
Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink Slim Baltagi
 
Why apache Flink is the 4G of Big Data Analytics Frameworks
Why apache Flink is the 4G of Big Data Analytics FrameworksWhy apache Flink is the 4G of Big Data Analytics Frameworks
Why apache Flink is the 4G of Big Data Analytics FrameworksSlim Baltagi
 

En vedette (6)

Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
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
 
CompletableFuture
CompletableFutureCompletableFuture
CompletableFuture
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8
 
Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink
 
Why apache Flink is the 4G of Big Data Analytics Frameworks
Why apache Flink is the 4G of Big Data Analytics FrameworksWhy apache Flink is the 4G of Big Data Analytics Frameworks
Why apache Flink is the 4G of Big Data Analytics Frameworks
 

Similaire à Completable future

Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8IndicThreads
 
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterLambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterJAXLondon2014
 
Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Simon Ritter
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8javafxpert
 
JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)
JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)
JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)Fred Rowe
 
Lambdas : Beyond The Basics
Lambdas : Beyond The BasicsLambdas : Beyond The Basics
Lambdas : Beyond The BasicsSimon Ritter
 
"Quantum" Performance Effects
"Quantum" Performance Effects"Quantum" Performance Effects
"Quantum" Performance EffectsSergey Kuksenko
 
Jakarta Concurrency: Present and Future
Jakarta Concurrency: Present and FutureJakarta Concurrency: Present and Future
Jakarta Concurrency: Present and FuturePayara
 
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_001Sven Ruppert
 
GlassFish BOF
GlassFish BOFGlassFish BOF
GlassFish BOFglassfish
 
Cloud Native Serverless Java — Orkhan Gasimov
Cloud Native Serverless Java — Orkhan GasimovCloud Native Serverless Java — Orkhan Gasimov
Cloud Native Serverless Java — Orkhan GasimovGlobalLogic Ukraine
 
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)Shing Wai Chan
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureJavaDayUA
 
2015 Java update and roadmap, JUG sevilla
2015  Java update and roadmap, JUG sevilla2015  Java update and roadmap, JUG sevilla
2015 Java update and roadmap, JUG sevillaTrisha Gee
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java PlatformSivakumar Thyagarajan
 
OTN Tour 2013: What's new in java EE 7
OTN Tour 2013: What's new in java EE 7OTN Tour 2013: What's new in java EE 7
OTN Tour 2013: What's new in java EE 7Bruno Borges
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Savio Sebastian
 
MySQL Proxy. A powerful, flexible MySQL toolbox.
MySQL Proxy. A powerful, flexible MySQL toolbox.MySQL Proxy. A powerful, flexible MySQL toolbox.
MySQL Proxy. A powerful, flexible MySQL toolbox.Miguel Araújo
 

Similaire à Completable future (20)

Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8
 
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterLambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
 
Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8
 
JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)
JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)
JSR 236 Concurrency Utils for EE presentation for JavaOne 2013 (CON7948)
 
Lambdas : Beyond The Basics
Lambdas : Beyond The BasicsLambdas : Beyond The Basics
Lambdas : Beyond The Basics
 
"Quantum" Performance Effects
"Quantum" Performance Effects"Quantum" Performance Effects
"Quantum" Performance Effects
 
Jakarta Concurrency: Present and Future
Jakarta Concurrency: Present and FutureJakarta Concurrency: Present and Future
Jakarta Concurrency: Present and Future
 
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
 
GlassFish BOF
GlassFish BOFGlassFish BOF
GlassFish BOF
 
Cloud Native Serverless Java — Orkhan Gasimov
Cloud Native Serverless Java — Orkhan GasimovCloud Native Serverless Java — Orkhan Gasimov
Cloud Native Serverless Java — Orkhan Gasimov
 
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and Architecture
 
2015 Java update and roadmap, JUG sevilla
2015  Java update and roadmap, JUG sevilla2015  Java update and roadmap, JUG sevilla
2015 Java update and roadmap, JUG sevilla
 
Java ee7 1hour
Java ee7 1hourJava ee7 1hour
Java ee7 1hour
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java Platform
 
OTN Tour 2013: What's new in java EE 7
OTN Tour 2013: What's new in java EE 7OTN Tour 2013: What's new in java EE 7
OTN Tour 2013: What's new in java EE 7
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
 
MySQL Proxy. A powerful, flexible MySQL toolbox.
MySQL Proxy. A powerful, flexible MySQL toolbox.MySQL Proxy. A powerful, flexible MySQL toolbox.
MySQL Proxy. A powerful, flexible MySQL toolbox.
 
Java Cloud and Container Ready
Java Cloud and Container ReadyJava Cloud and Container Ready
Java Cloud and Container Ready
 

Dernier

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 SoftwareJim McKeeth
 
%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 sowetomasabamasaba
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
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...WSO2
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%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 Stilfonteinmasabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
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?WSO2
 
+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
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
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 2024VictoriaMetrics
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 

Dernier (20)

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
 
%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
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
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...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%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
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
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?
 
+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...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
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
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 

Completable future

  • 1.
  • 2.
  • 3. Completable Future Srinivasan Raghavan Senior Member of Technical Staff Java Platform Group Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
  • 4. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Program Agenda java.util.Future Introduction Cloud Services Design and the fight for Performance CompletableFuture and power of parallelism Building powerful libraries with Completable Future 1 2 3 4 4
  • 5. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | java.util.Future Introduction • Before jdk1.5 , no java.util.concurrent.*, only threads ,synchronized primitives • W ite o e , u a ywhe e ? – g eat su ess , But u it a illio ti es , wo k the sa e ? ig uestio • In came java.util.concurrent.* with executor service and future tasks and many other concurrency constructs • A java.util.Future is a construct which holds a result available at a later time • Future is asynchronous , but its not non-blocking 5
  • 6. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | The Executor Service and Future Task • Executors contains pool of threads which accepts tasks and supplies to the Future • When a task is submitted to the executor it returns a future and future.get() would block the computation until it ends 6 ExecutorService executorService = Executors.newFixedThreadPool(20); Future<Integer> future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { return 42; } }); System.out.println(future.get()); executorService.shutdown(); User Executor Task (Callable) Future
  • 7. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | What can be done ? • Future can allow computation in the background so improving performance • Future.get() would block the thread and wait till the computation is complete and get the result • Can get an exception if there is a failure • future.cancel() cancels the computation • future.isDone() checks the computation is complete • A d that’s it ///// 7 ExecutorService executorService = Executors.newFixedThreadPool(20); Future<Integer> future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { //Some complex work return 42; } }); System.out.println(future.get()); executorService.shutdown();
  • 8. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Distributed Cloud Services Design and the fight for Performance 8
  • 9. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | A Typical distributed cloud service 9 Get data from service provider 1 Get data from service provider 3 Get data from service provider 2 Combine Data Response(result) Request(userData,reuestParams) Processing for analytics Process data for the user Generate recommendation
  • 10. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Performance Bottlenecks and impacts • Java.util.Future can help in parallelism • But it cannot help with pipeline the tasks and managing the thread pool for you • Future does not supports call backs and chaining of operations • Building libraries with future can be complictaed • Performing in a serial way can impact the latency big time • It can destroy all benefits of having distributed services • No amount of horizontal and vertical scaling can help • Without dynamic services offerings business can be affected 10
  • 11. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | CompletableFuture and power of parallelism 11
  • 12. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | What is Completable future ? • Its new addition to java 8 • Asynchronous, allows registering asyc callbacks just like java scripts, event-driven programming model • Support for depending functions to be triggered on completion • Each stage can be executed with different executor pool • Also comes with a built in thread pool for executing tasks • Built in lambda support ,super flexible and scalable api 12
  • 13. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Basics 13 CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() { @Override public String get() { // ...long running... return "42"; } }, executor1); future.get(); //Come on ... we are in JDK 8 !!! CompletableFuture<String> future = CompletableFuture .supplyAsync(() -> "42",executor1); future.get();
  • 14. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Lambdas , Crash Recap 14
  • 15. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Lambdas • Function definition that is not bound to an identifier 15 /** * * This is a piece of code that illustrate how lambdas work in Java 8 * * Given an example * * f(x) = 2x+5; * * given x= 2 ; f(x) = 9 ; * * z(x)= f(g(x)) where g(x) =3x+5 * * z(x) = 2(3x+5) +5 = 6x+15 12+15 = 27 * * */ public class LambdaUnderStanding2 { @FunctionalInterface static interface Funct { int apply(int x); default Funct compose(Funct before) { return (x) -> apply(before.apply(x)); } } public static void main(String[] args) { Funct annoymous = new Funct() { @Override public int apply(int x) { return 2 * x + 5;; } }; Funct funct = (x) -> 2 * x + 5; System.out.println(funct.apply(2)); Funct composed = funct.compose((x) -> 3 * x + 5); System.out.println(composed.apply(2)); } }
  • 16. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Java 8 Functional Interface 16 Predicate<Integer> test = (x) -> x> 10; Function<Integer, Integer> function = (x) -> 3 * x + 5; Consumer<Integer> print = (x) -> System.out.println(x); BiFunction<Integer, Integer, Integer> biFunction = (x, y) -> 3 * x + 4* y + 2; Supplier<Integer> supplier = () -> Integer.MAX_VALUE;
  • 17. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | thenApply() -transformations 17 /** * Classic call back present in javascript or scala . * theApply is like run this function when the result *arrives from previous stages */ final CompletableFuture<Integer> future1 = CompletableFuture .supplyAsync(() -> "42", executor1).thenApply( (x) -> Integer.parseInt(x)); /** * thenApply is trasformative changing CompletableFuture<Integer> to * CompletableFuture<Double> */ CompletableFuture<Double> future2 = CompletableFuture .supplyAsync(() -> "42", executor1) .thenApply((x) -> Integer.parseInt(x)) .thenApply(r -> r * r * Math.PI); /** * U can supply a differnt executor pool for thenApply */ CompletableFuture<Double> future = CompletableFuture .supplyAsync(() -> "42", executor1) .thenApplyAsync((x) -> Integer.parseInt(x), executor2) .thenApplyAsync(r -> r * r * Math.PI, executor2);
  • 18. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | thenCombine() , whenComplete() –completion 18 final CompletableFuture<Integer> future = CompletableFuture .supplyAsync(() -> "32", executor1).thenApply( (x) -> Integer.parseInt(x)); CompletableFuture.supplyAsync(() -> "42", executor2) .thenApply((x) -> Integer.parseInt(x)) .thenCombine(future, (x, y) -> x + y) .thenAccept((result) -> System.out.println(result)); /** * When complete is final stage where it can check the execpetions * propagated and pass results through it */ final CompletableFuture<Integer> future = CompletableFuture .supplyAsync(() -> "42", executor1) .thenApply((x) -> Integer.parseInt(x)) .whenComplete( (x, throwable) -> { if (throwable != null) { Logger.getAnonymousLogger().log(Level.SEVERE, "Logging" + throwable); } else { Logger.getAnonymousLogger().log(Level.FINE, " Passed " + x); } });
  • 19. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | thenCombine() allOf() - combining futures 19 /** * Combining two dependent futures */ final CompletableFuture<Integer> future = CompletableFuture .supplyAsync(() -> "32", executor1).thenApply( (x) -> Integer.parseInt(x)); CompletableFuture.supplyAsync(() -> "42", executor2) .thenApply((x) -> Integer.parseInt(x)) .thenCombine(future, (x, y) -> x + y) .thenAccept((result) -> System.out.println(result)); /** * Combining n futures unrelated */ CompletableFuture<Void> future2 = CompletableFuture .supplyAsync(() -> "42", executor1) .thenApplyAsync((x) -> Integer.parseInt(x), executor2) .thenAcceptAsync( (x) -> Logger.getAnonymousLogger().log(Level.FINE, "Logging" + x), executor2); CompletableFuture<Void> future1 = CompletableFuture .supplyAsync(() -> “ ", executor1) .thenApplyAsync((x) -> Integer.parseInt(x), executor2) .thenAcceptAsync( (x) -> Logger.getAnonymousLogger().log(Level.FINE, "Logging" + x), executor2); CompletableFuture.allOf(future1,future2).join();
  • 20. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Building powerful libraries with Completable Future 20
  • 21. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Building powerful libraries with completable futures • Building scalable service orchestrator • Building dynamic http client framework • Improve parallelism in existing services with are done serial • Building libraries tuned for vertical scalability 21
  • 22. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | References • https://docs.oracle.com/javase/tutorial/ • https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Completa bleFuture.html • http://cs.oswego.edu/mailman/listinfo/concurrency-interest • https://github.com/srinivasanraghavan/functional 22
  • 23. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Questions ? 23