SlideShare a Scribd company logo
1 of 60
Download to read offline
Leveraging CompletableFutures to handle
your query results asynchronously
David Gómez G.


Developer Advocate
Concurrency


vs


Parallelism
Same type of tasks


Workload split between similar workers


Have the work finished before
Parallelism Concurrency
Different type of tasks


Usually do some works while waiting for
other tasks to be completed.


Have the work finished before
@DGOMEZG
Java and Concurrency
Lots of tools since Java 1
Java has (basic) building blocks for Concurrency and parallelism
since Java 1.


Even when most desktop computers were single-core
@DGOMEZG
Threads
Very Expensive
Thread t = new Thread(task);

t.start();

t.join();

Easily forgotten
Blocking call
ThreadPools
@DGOMEZG
ThreadPools
@DGOMEZG
ThreadPools
@DGOMEZG
ThreadPools
@DGOMEZG
ThreadPools
@DGOMEZG
Since Java 5
Concurrency & parallelism support improved in Java 5


Lots of New Concurrency constructors


New concurrent-friendly Data Structures


Revisited and improved in Java 7, 8, 9 …


More coming up as part of loom project
@DGOMEZG
Running tasks
asynchronously
ExecutorService
And now we can submit:


- tasks that do not return anything. Runnable


- tasks that return a result. Callable<R>


Executor Service returns a Future<R>
@DGOMEZG
ExecutorService & Future<T>
ExecutorService executorService = Executors.newCachedThreadPool();

Future<String> taskResult = 

executorService.submit(longRunningTaskWithResult);
String s = taskResult.get();
Blocking call
ExecutorService & Future<T>
ExecutorService executorService = Executors.newCachedThreadPool();

Future<String> taskResult = 

executorService.submit(longRunningTaskWithResult);
while (!taskResult.isDone()) {

doSomethingElse();

}

String s = taskResult.get();

False while task is not cancelled
nor
fi
nished
Improving performance by doing
other tasks.
Running Multiple T
asks
List<Future<String
>
>
taskResults = new ArrayList
<
>
();

for (Callable<String> task : tasks) {

taskResults.add(executorService.submit(task));

}

for (Future<String> result : taskResults) {

processResult(result.get());

}

Bene
fi
t only between submitting
all tasks and getting the results
Running Heterogeneous T
asks
List<Future<String
>
>
taskResults = new ArrayList
<
>
();

for (Callable<String> task : tasks) {

taskResults.add(executorService.submit(task));

}

for (Future<String> result : taskResults) {

processResult(result.get());

}
 What if task1 is too slow
while task2 is fast?
What if we need the result of
task1 to submit task2?
(CompletionService returns
tasks in the order they are
fi
nished)
CompletableFuture
CompletableFuture<T>
Introduced in Java8


Has specific methods to submit tasks to an ExecutorService


Implements a fluent API (CompletionStage) that allows chaining and
combining dependant tasks.


Allow to use different sized ExecutorServices for different tasks.
@DGOMEZG
Async with CompletableFuture
CompletableFuture.runAsync(getLongRunningTaskWithNoResult());
Async with CompletableFuture
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult());

doSomethingElse();
Async with CompletableFuture
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult());

doSomethingElse();

CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult());

doSomethingElse();

voidCF.get();
/
/
Wait until background task is finished
Async with CompletableFuture
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult());

doSomethingElse();

voidCF.get();
/
/
Wait until background task is finished
private static final Executor ASYNC_POOL = USE_COMMON_POOL ?

ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
Async with CompletableFuture
private static final Executor ASYNC_POOL = USE_COMMON_POOL ?

ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
Shared with the JVM (may affect parallel
streams)


Sized for CPU intensive tasks (if our task is
IO bound, we may affect app performance)


Daemon Threads (if our main thread
finishes, tasks may not be executed)
Same that


new Thread(task).start();
Async with CompletableFuture
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult());

doSomethingElse();

voidCF.get();
/
/
Wait until background task is finished
private static final Executor ASYNC_POOL = USE_COMMON_POOL ?

ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
Async with CompletableFuture
ExecutorService executorService = Executors.newCachedThreadPool();

executorService
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult());

doSomethingElse();

voidCF.get();
/
/
Wait until background task is finished
Async with CompletableFuture
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult()

, );

doSomethingElse();

voidCF.get();
/
/
Wait until background task is finished
ExecutorService executorService = Executors.newCachedThreadPool();

executorService
Sized and used for the expected % of CPU used by
your tasks
Async with CompletableFuture
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult()

, );

doSomethingElse();

voidCF.get();
/
/
Wait until background task is finished
ExecutorService executorService = Executors.newCachedThreadPool();

executorService
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult()

, );

doSomethingElse();

voidCF.get();
/
/
Wait until background task is finished
NoResult()
Async with CompletableFuture
ExecutorService executorService = Executors.newCachedThreadPool();

executorService
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult()

, );

doSomethingElse();

voidCF.get();
/
/
Wait until background task is finished
NoResult()
Async with CompletableFuture
ExecutorService executorService = Executors.newCachedThreadPool();

executorService
Result()
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult()

, );

doSomethingElse();

voidCF.get();
/
/
Wait until background task is finished
Result()
Async with CompletableFuture
ExecutorService executorService = Executors.newCachedThreadPool();

executorService
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult()

, );

doSomethingElse();

voidCF.get();
/
/
Wait until background task is finished
sup Result()
Async with CompletableFuture
ExecutorService executorService = Executors.newCachedThreadPool();

executorService
Void> voidCF =
Async(getLongRunningTaskWithResult()
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult()

, );

doSomethingElse();

voidCF.get();
/
/
Wait until background task is finished
sup Async(getLongRunningTaskWithResult()
Async with CompletableFuture
ExecutorService executorService = Executors.newCachedThreadPool();

executorService
Void> voidCF =
ply
CompletableFuture<Void> voidCF = 

CompletableFuture.runAsync(getLongRunningTaskWithNoResult()

, );

doSomethingElse();

result.get();
/
/
Wait until background task is finished
String> result =
sup Async(getLongRunningTaskWithResult()
Async with CompletableFuture
ExecutorService executorService = Executors.newCachedThreadPool();

executorService
ply
CompletableFuture<T>
It may seem just an alternative to Future<T>
public class CompletableFuture<T> 

implements Future<T>, CompletionStage<T>
CompletionStage<T>
@DGOMEZG
CompletionStage<T>
CompletableFuture<T>
Fluent API to chain, compose and combine Futures.
@DGOMEZG
Chaining tasks (blocking)
void invokeSlowProcess() {

Order order = orderService.getOrder();

customerChecker.authorized(order.customer());

}
@DGOMEZG
executed by main in PT7.045928S
invokeSlowServiceDependantTasks();
Chaining tasks with CompletableFuture
@DGOMEZG
CompletableFuture

.supplyAsync(

()
-
>
orderService.getOrder()

).thenAcceptAsync(

order
-
>
customerChecker.authorized(order.customer())

);

Submitted by main in PT0.058982S


Executed by ForkJoinPool.commonPool-worker-1 in PT2.008558S


Executed by ForkJoinPool.commonPool-worker-2 in PT5.010714S
Chaining parallel tasks
@DGOMEZG
Chaining tasks
var orderCF = CompletableFuture.supplyAsync(

()
-
>
orderService.getOrder()

);

orderCF.thenAcceptAsync(

order
-
>
activityTracker.orderAccessed(order)));

orderCF.thenAcceptAsync(

order
-
>
customerChecker.authorized(order.customer())));

@DGOMEZG
Submitted by main in PT0.071653S


getOrder executed by ForkJoinPool.commonPool-worker-1 in PT2.006599S


activityTracker executed by ForkJoinPool.commonPool-worker-3 in PT2.009098S


customerChecker executed by ForkJoinPool.commonPool-worker-2 in PT5.007562S
Chaining multiple parallel tasks
@DGOMEZG
Chaining multiple parallel tasks
@DGOMEZG
var orderCF = CompletableFuture.supplyAsync(

()
-
>
orderService.getOrder()

);

orderCF.thenAcceptAsync(

order
-
>
customerChecker.authorized(order.customer())));

orderWithCF.thenAcceptAsync(order
-
>
{

order.items().stream()

.map(orderItem
-
>


CompletableFuture.supplyAsync( ()
-
>


inventoryService.checkAvailability(

orderItem.productId(), 

orderItem.quantity()))

).collect(Collectors.toList())

.forEach(CompletableFuture
:
:
join);

});
CompletableFuture<T>
Fluent API to chain, compose and combine Futures.
CompletionStage<T>
acceptEither

applyToEither

runAfterEither

runAfterBoth

thenAccept

thenAcceptBoth

thenRun

thenCombine

thenCompose

whenAccept

@DGOMEZG
CompletableFuture


In your API
Why should you consider using CompletableFuture
in you API?
Enable your users to maximise the performance to your queries.


And keep control on how you execute the asynchronous tasks.


Benefit from how other frameworks handle CompletableFutures
(i. e Spring)
@DGOMEZG
Creating and managing CompletableFutures
CompletableFuture<String> completableFuture = 

new CompletableFuture
<
>
();
@DGOMEZG
Creating and managing CompletableFutures
@DGOMEZG
Creating and managing CompletableFutures
@DGOMEZG
@DGOMEZG
An Example: QueryBus at AxonFramework
Queries
UI / API
Commands
Command Model
Projections
Events
An Example: QueryBus at AxonFramework
UI / API
Projections
queryMessage
@DGOMEZG
QueryBus
QueryBusImpl (simplified)
public CompletableFuture<QueryResponseMessage> query(QueryMessage query) {

/
/
Create your CompletableFuture

/
/
Prepare to Run asynchronously

/
/
get Results/Exceptions to complete the future

/
/
return your completableFuture

}
QueryBusImpl (simplified)
public CompletableFuture<QueryResponseMessage> query(QueryMessage query) {

/
/
Create your CompletableFuture

CompletableFuture<QueryResponseMessage> queryTransaction = 

new CompletableFuture
<
>
();

/
/
Prepare to Run asynchronously

/
/
get Results/Exceptions to complete the future

/
/
return your completableFuture

return queryTransaction;

}
QueryBusImpl (simplified)
public CompletableFuture<QueryResponseMessage> query(QueryMessage query) {

CompletableFuture<QueryResponseMessage> queryTransaction = 

new CompletableFuture
<
>
();

try {

/
/
Prepare to Run asynchronously

/
/
get Results to complete the future

} catch (Exception e) {

queryTransaction.completeExceptionally(exception);

}

return queryTransaction;

}
QueryBusImpl (simplified)
public CompletableFuture<QueryResponseMessage> query(QueryMessage query) {

CompletableFuture<QueryResponseMessage> queryTransaction = 

new CompletableFuture
<
>
();

try {

ResultStream<QueryResponse> result =

axonServerConnectionManager.getConnection(targetContext)

.query(query);

/
*
.
.
.
*
/


result.onAvailable(()
-
>


queryTransaction.complete(result.nextIfAvailable())

} catch (Exception e) {

queryTransaction.completeExceptionally(exception);

}

return queryTransaction;

}
Benefits
It allows to compose asynchronous query calls to different systems
@DGOMEZG
private final QueryGateway queryGateway;

@GetMapping("orders/{OrderId}/status")

public Future<OrderStatus> orderStatus(@PathVariable String orderId) {

CompletableFuture<OrderStatus> orderStatusCF =

queryGateway.query(new OrderStatusQuery(orderId),

new InstanceResponseType
<
>
(OrderStatus.class));

/
/
Invoke other external services asynchronously 

/
/
Composing the tasks with CompletionStage.*

/
/
Useful in processes when applying the "Strangling The monolith Pattern”

/
/
Probably not very usual when using DDD 



return orderStatusCF;

}
Benefits
SpringFramework knows how to return a Future<T>


Tomcat (and most application Servers) can handle better the Threads in the ThreadPool
@DGOMEZG
private final QueryGateway queryGateway;

@GetMapping(“orders/{OrderId}/status")

public Future<OrderStatus> orderStatus(@PathVariable String orderId) {

return CompletableFuture<OrderStatus> orderStatusCF =

queryGateway.query(new OrderStatusQuery(orderId),

new InstanceResponseType
<
>
(OrderStatus.class));

}
Conclusions
Conclusions
CompletableFutures are a powerful tool to compose and combine
Asynchronous execution of heterogeneous tasks


Best if used with specific ExecutorService instances, properly sized based
depending on amount of I/O-Wait time


Adding CompletableFutures on you Async API will give more powers to the
developers using your library/framework.
@DGOMEZG
Where do I go from here?
https://github.com/AxonFramework/AxonFramework
Quick Start Tutorial.


https://docs.axoniq.io/reference-guide/getting-started/quick-start
Free Courses on DDD, CQRS, Event-Sourcing


https://academy.axoniq.io/
https:/
/lp.axoniq.io/devnexus-22
The slides
JavaSpecialists newsletter
Java Concurrency Specialist Courses

More Related Content

What's hot

Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Fwdays
 
HBase and HDFS: Understanding FileSystem Usage in HBase
HBase and HDFS: Understanding FileSystem Usage in HBaseHBase and HDFS: Understanding FileSystem Usage in HBase
HBase and HDFS: Understanding FileSystem Usage in HBaseenissoz
 
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...HostedbyConfluent
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - IntroductionKnoldus Inc.
 
Redis cluster
Redis clusterRedis cluster
Redis clusteriammutex
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to RedisDvir Volk
 
MongoDB presentation
MongoDB presentationMongoDB presentation
MongoDB presentationHyphen Call
 
Introduction to Kafka and Zookeeper
Introduction to Kafka and ZookeeperIntroduction to Kafka and Zookeeper
Introduction to Kafka and ZookeeperRahul Jain
 
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...Flink Forward
 
MySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKMySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKYoungHeon (Roy) Kim
 
Apache Kafka - Messaging System Overview
Apache Kafka - Messaging System OverviewApache Kafka - Messaging System Overview
Apache Kafka - Messaging System OverviewDmitry Tolpeko
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event EmittersTheCreativedev Blog
 
DNS Security Presentation ISSA
DNS Security Presentation ISSADNS Security Presentation ISSA
DNS Security Presentation ISSASrikrupa Srivatsan
 
Rabbitmq & Kafka Presentation
Rabbitmq & Kafka PresentationRabbitmq & Kafka Presentation
Rabbitmq & Kafka PresentationEmre Gündoğdu
 
Introduction to Apache ZooKeeper
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeperSaurav Haloi
 
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John FallowsEnd-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John FallowsHostedbyConfluent
 

What's hot (20)

MongodB Internals
MongodB InternalsMongodB Internals
MongodB Internals
 
Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"
 
HBase and HDFS: Understanding FileSystem Usage in HBase
HBase and HDFS: Understanding FileSystem Usage in HBaseHBase and HDFS: Understanding FileSystem Usage in HBase
HBase and HDFS: Understanding FileSystem Usage in HBase
 
kafka
kafkakafka
kafka
 
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - Introduction
 
Redis cluster
Redis clusterRedis cluster
Redis cluster
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
MongoDB presentation
MongoDB presentationMongoDB presentation
MongoDB presentation
 
Project Reactor By Example
Project Reactor By ExampleProject Reactor By Example
Project Reactor By Example
 
Introduction to Kafka and Zookeeper
Introduction to Kafka and ZookeeperIntroduction to Kafka and Zookeeper
Introduction to Kafka and Zookeeper
 
Intro to HBase
Intro to HBaseIntro to HBase
Intro to HBase
 
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
 
MySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKMySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELK
 
Apache Kafka - Messaging System Overview
Apache Kafka - Messaging System OverviewApache Kafka - Messaging System Overview
Apache Kafka - Messaging System Overview
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
DNS Security Presentation ISSA
DNS Security Presentation ISSADNS Security Presentation ISSA
DNS Security Presentation ISSA
 
Rabbitmq & Kafka Presentation
Rabbitmq & Kafka PresentationRabbitmq & Kafka Presentation
Rabbitmq & Kafka Presentation
 
Introduction to Apache ZooKeeper
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeper
 
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John FallowsEnd-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
 

Similar to Leverage CompletableFutures to handle async queries. DevNexus 2022

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 AsynchrhonouslyDavid Gómez García
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingOliver Scheer
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
JSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJeff Fox
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsSrikanth Shenoy
 
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 concurrencykshanth2101
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & PromisesKnoldus Inc.
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Yoshifumi Kawai
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actorsbloodredsun
 
CompletableFuture
CompletableFutureCompletableFuture
CompletableFuturekoji lin
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async futureslicejs
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
 
State in stateless serverless functions
State in stateless serverless functionsState in stateless serverless functions
State in stateless serverless functionsAlex Pshul
 

Similar to Leverage CompletableFutures to handle async queries. DevNexus 2022 (20)

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
 
Owin
OwinOwin
Owin
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
JSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery Deferred
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
 
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
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
 
CompletableFuture
CompletableFutureCompletableFuture
CompletableFuture
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Gwt and Xtend
Gwt and XtendGwt and Xtend
Gwt and Xtend
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 
Completable future
Completable futureCompletable future
Completable future
 
State in stateless serverless functions
State in stateless serverless functionsState in stateless serverless functions
State in stateless serverless functions
 

More from David Gómez García

Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...David Gómez García
 
Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...David Gómez García
 
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021David Gómez García
 
Cdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integrationCdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integrationDavid Gómez García
 
What's in a community like Liferay's
What's in a community like Liferay'sWhat's in a community like Liferay's
What's in a community like Liferay'sDavid Gómez García
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadDavid Gómez García
 
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTRT3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTRDavid Gómez García
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring SessionDavid Gómez García
 
Construccion de proyectos con gradle
Construccion de proyectos con gradleConstruccion de proyectos con gradle
Construccion de proyectos con gradleDavid Gómez García
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)David Gómez García
 
Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. David Gómez García
 
El poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesaníaEl poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesaníaDavid Gómez García
 
HDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript ScriptingHDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript ScriptingDavid Gómez García
 
A real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodbA real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodbDavid Gómez García
 

More from David Gómez García (20)

Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...
 
Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...
 
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
 
Cdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integrationCdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integration
 
What's in a community like Liferay's
What's in a community like Liferay'sWhat's in a community like Liferay's
What's in a community like Liferay's
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
 
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTRT3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
Construccion de proyectos con gradle
Construccion de proyectos con gradleConstruccion de proyectos con gradle
Construccion de proyectos con gradle
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
 
Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min.
 
Spring4 whats up doc?
Spring4 whats up doc?Spring4 whats up doc?
Spring4 whats up doc?
 
Gradle como alternativa a maven
Gradle como alternativa a mavenGradle como alternativa a maven
Gradle como alternativa a maven
 
El poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesaníaEl poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesanía
 
Geo-SentimentZ
Geo-SentimentZGeo-SentimentZ
Geo-SentimentZ
 
HDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript ScriptingHDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript Scripting
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
A real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodbA real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodb
 

Recently uploaded

chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 

Recently uploaded (20)

chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 

Leverage CompletableFutures to handle async queries. DevNexus 2022

  • 1. Leveraging CompletableFutures to handle your query results asynchronously David Gómez G. Developer Advocate
  • 3. Same type of tasks Workload split between similar workers Have the work finished before Parallelism Concurrency Different type of tasks Usually do some works while waiting for other tasks to be completed. Have the work finished before @DGOMEZG
  • 5. Lots of tools since Java 1 Java has (basic) building blocks for Concurrency and parallelism since Java 1. Even when most desktop computers were single-core @DGOMEZG
  • 6. Threads Very Expensive Thread t = new Thread(task); t.start(); t.join(); Easily forgotten Blocking call
  • 12. Since Java 5 Concurrency & parallelism support improved in Java 5 Lots of New Concurrency constructors New concurrent-friendly Data Structures Revisited and improved in Java 7, 8, 9 … More coming up as part of loom project @DGOMEZG
  • 14. ExecutorService And now we can submit: - tasks that do not return anything. Runnable - tasks that return a result. Callable<R> Executor Service returns a Future<R> @DGOMEZG
  • 15. ExecutorService & Future<T> ExecutorService executorService = Executors.newCachedThreadPool(); Future<String> taskResult = executorService.submit(longRunningTaskWithResult); String s = taskResult.get(); Blocking call
  • 16. ExecutorService & Future<T> ExecutorService executorService = Executors.newCachedThreadPool(); Future<String> taskResult = executorService.submit(longRunningTaskWithResult); while (!taskResult.isDone()) { doSomethingElse(); } String s = taskResult.get(); False while task is not cancelled nor fi nished Improving performance by doing other tasks.
  • 17. Running Multiple T asks List<Future<String > > taskResults = new ArrayList < > (); for (Callable<String> task : tasks) { taskResults.add(executorService.submit(task)); } for (Future<String> result : taskResults) { processResult(result.get()); } Bene fi t only between submitting all tasks and getting the results
  • 18. Running Heterogeneous T asks List<Future<String > > taskResults = new ArrayList < > (); for (Callable<String> task : tasks) { taskResults.add(executorService.submit(task)); } for (Future<String> result : taskResults) { processResult(result.get()); } What if task1 is too slow while task2 is fast? What if we need the result of task1 to submit task2? (CompletionService returns tasks in the order they are fi nished)
  • 20. CompletableFuture<T> Introduced in Java8 Has specific methods to submit tasks to an ExecutorService Implements a fluent API (CompletionStage) that allows chaining and combining dependant tasks. Allow to use different sized ExecutorServices for different tasks. @DGOMEZG
  • 22. Async with CompletableFuture CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult()); doSomethingElse();
  • 23. Async with CompletableFuture CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult()); doSomethingElse(); CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult()); doSomethingElse(); voidCF.get(); / / Wait until background task is finished
  • 24. Async with CompletableFuture CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult()); doSomethingElse(); voidCF.get(); / / Wait until background task is finished private static final Executor ASYNC_POOL = USE_COMMON_POOL ? ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
  • 25. Async with CompletableFuture private static final Executor ASYNC_POOL = USE_COMMON_POOL ? ForkJoinPool.commonPool() : new ThreadPerTaskExecutor(); Shared with the JVM (may affect parallel streams) Sized for CPU intensive tasks (if our task is IO bound, we may affect app performance) Daemon Threads (if our main thread finishes, tasks may not be executed) Same that new Thread(task).start();
  • 26. Async with CompletableFuture CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult()); doSomethingElse(); voidCF.get(); / / Wait until background task is finished private static final Executor ASYNC_POOL = USE_COMMON_POOL ? ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
  • 27. Async with CompletableFuture ExecutorService executorService = Executors.newCachedThreadPool(); executorService CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult()); doSomethingElse(); voidCF.get(); / / Wait until background task is finished
  • 28. Async with CompletableFuture CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult() , ); doSomethingElse(); voidCF.get(); / / Wait until background task is finished ExecutorService executorService = Executors.newCachedThreadPool(); executorService Sized and used for the expected % of CPU used by your tasks
  • 29. Async with CompletableFuture CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult() , ); doSomethingElse(); voidCF.get(); / / Wait until background task is finished ExecutorService executorService = Executors.newCachedThreadPool(); executorService
  • 30. CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult() , ); doSomethingElse(); voidCF.get(); / / Wait until background task is finished NoResult() Async with CompletableFuture ExecutorService executorService = Executors.newCachedThreadPool(); executorService
  • 31. CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult() , ); doSomethingElse(); voidCF.get(); / / Wait until background task is finished NoResult() Async with CompletableFuture ExecutorService executorService = Executors.newCachedThreadPool(); executorService Result()
  • 32. CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult() , ); doSomethingElse(); voidCF.get(); / / Wait until background task is finished Result() Async with CompletableFuture ExecutorService executorService = Executors.newCachedThreadPool(); executorService
  • 33. CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult() , ); doSomethingElse(); voidCF.get(); / / Wait until background task is finished sup Result() Async with CompletableFuture ExecutorService executorService = Executors.newCachedThreadPool(); executorService Void> voidCF = Async(getLongRunningTaskWithResult()
  • 34. CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult() , ); doSomethingElse(); voidCF.get(); / / Wait until background task is finished sup Async(getLongRunningTaskWithResult() Async with CompletableFuture ExecutorService executorService = Executors.newCachedThreadPool(); executorService Void> voidCF = ply
  • 35. CompletableFuture<Void> voidCF = CompletableFuture.runAsync(getLongRunningTaskWithNoResult() , ); doSomethingElse(); result.get(); / / Wait until background task is finished String> result = sup Async(getLongRunningTaskWithResult() Async with CompletableFuture ExecutorService executorService = Executors.newCachedThreadPool(); executorService ply
  • 36. CompletableFuture<T> It may seem just an alternative to Future<T> public class CompletableFuture<T> implements Future<T>, CompletionStage<T> CompletionStage<T> @DGOMEZG
  • 37. CompletionStage<T> CompletableFuture<T> Fluent API to chain, compose and combine Futures. @DGOMEZG
  • 38. Chaining tasks (blocking) void invokeSlowProcess() { Order order = orderService.getOrder(); customerChecker.authorized(order.customer()); } @DGOMEZG executed by main in PT7.045928S invokeSlowServiceDependantTasks();
  • 39. Chaining tasks with CompletableFuture @DGOMEZG CompletableFuture .supplyAsync( () - > orderService.getOrder() ).thenAcceptAsync( order - > customerChecker.authorized(order.customer()) ); Submitted by main in PT0.058982S Executed by ForkJoinPool.commonPool-worker-1 in PT2.008558S Executed by ForkJoinPool.commonPool-worker-2 in PT5.010714S
  • 41. Chaining tasks var orderCF = CompletableFuture.supplyAsync( () - > orderService.getOrder() ); orderCF.thenAcceptAsync( order - > activityTracker.orderAccessed(order))); orderCF.thenAcceptAsync( order - > customerChecker.authorized(order.customer()))); @DGOMEZG Submitted by main in PT0.071653S getOrder executed by ForkJoinPool.commonPool-worker-1 in PT2.006599S activityTracker executed by ForkJoinPool.commonPool-worker-3 in PT2.009098S customerChecker executed by ForkJoinPool.commonPool-worker-2 in PT5.007562S
  • 42. Chaining multiple parallel tasks @DGOMEZG
  • 43. Chaining multiple parallel tasks @DGOMEZG var orderCF = CompletableFuture.supplyAsync( () - > orderService.getOrder() ); orderCF.thenAcceptAsync( order - > customerChecker.authorized(order.customer()))); orderWithCF.thenAcceptAsync(order - > { order.items().stream() .map(orderItem - > CompletableFuture.supplyAsync( () - > inventoryService.checkAvailability( orderItem.productId(), orderItem.quantity())) ).collect(Collectors.toList()) .forEach(CompletableFuture : : join); });
  • 44. CompletableFuture<T> Fluent API to chain, compose and combine Futures. CompletionStage<T> acceptEither applyToEither runAfterEither runAfterBoth thenAccept thenAcceptBoth thenRun thenCombine thenCompose whenAccept @DGOMEZG
  • 46. Why should you consider using CompletableFuture in you API? Enable your users to maximise the performance to your queries. And keep control on how you execute the asynchronous tasks. Benefit from how other frameworks handle CompletableFutures (i. e Spring) @DGOMEZG
  • 47. Creating and managing CompletableFutures CompletableFuture<String> completableFuture = new CompletableFuture < > (); @DGOMEZG
  • 48. Creating and managing CompletableFutures @DGOMEZG
  • 49. Creating and managing CompletableFutures @DGOMEZG
  • 50. @DGOMEZG An Example: QueryBus at AxonFramework Queries UI / API Commands Command Model Projections Events
  • 51. An Example: QueryBus at AxonFramework UI / API Projections queryMessage @DGOMEZG QueryBus
  • 52. QueryBusImpl (simplified) public CompletableFuture<QueryResponseMessage> query(QueryMessage query) { / / Create your CompletableFuture / / Prepare to Run asynchronously / / get Results/Exceptions to complete the future / / return your completableFuture }
  • 53. QueryBusImpl (simplified) public CompletableFuture<QueryResponseMessage> query(QueryMessage query) { / / Create your CompletableFuture CompletableFuture<QueryResponseMessage> queryTransaction = new CompletableFuture < > (); / / Prepare to Run asynchronously / / get Results/Exceptions to complete the future / / return your completableFuture return queryTransaction; }
  • 54. QueryBusImpl (simplified) public CompletableFuture<QueryResponseMessage> query(QueryMessage query) { CompletableFuture<QueryResponseMessage> queryTransaction = new CompletableFuture < > (); try { / / Prepare to Run asynchronously / / get Results to complete the future } catch (Exception e) { queryTransaction.completeExceptionally(exception); } return queryTransaction; }
  • 55. QueryBusImpl (simplified) public CompletableFuture<QueryResponseMessage> query(QueryMessage query) { CompletableFuture<QueryResponseMessage> queryTransaction = new CompletableFuture < > (); try { ResultStream<QueryResponse> result = axonServerConnectionManager.getConnection(targetContext) .query(query); / * . . . * / result.onAvailable(() - > queryTransaction.complete(result.nextIfAvailable()) } catch (Exception e) { queryTransaction.completeExceptionally(exception); } return queryTransaction; }
  • 56. Benefits It allows to compose asynchronous query calls to different systems @DGOMEZG private final QueryGateway queryGateway; @GetMapping("orders/{OrderId}/status") public Future<OrderStatus> orderStatus(@PathVariable String orderId) { CompletableFuture<OrderStatus> orderStatusCF = queryGateway.query(new OrderStatusQuery(orderId), new InstanceResponseType < > (OrderStatus.class)); / / Invoke other external services asynchronously / / Composing the tasks with CompletionStage.* / / Useful in processes when applying the "Strangling The monolith Pattern” / / Probably not very usual when using DDD return orderStatusCF; }
  • 57. Benefits SpringFramework knows how to return a Future<T> Tomcat (and most application Servers) can handle better the Threads in the ThreadPool @DGOMEZG private final QueryGateway queryGateway; @GetMapping(“orders/{OrderId}/status") public Future<OrderStatus> orderStatus(@PathVariable String orderId) { return CompletableFuture<OrderStatus> orderStatusCF = queryGateway.query(new OrderStatusQuery(orderId), new InstanceResponseType < > (OrderStatus.class)); }
  • 59. Conclusions CompletableFutures are a powerful tool to compose and combine Asynchronous execution of heterogeneous tasks Best if used with specific ExecutorService instances, properly sized based depending on amount of I/O-Wait time Adding CompletableFutures on you Async API will give more powers to the developers using your library/framework. @DGOMEZG
  • 60. Where do I go from here? https://github.com/AxonFramework/AxonFramework Quick Start Tutorial. 
 https://docs.axoniq.io/reference-guide/getting-started/quick-start Free Courses on DDD, CQRS, Event-Sourcing 
 https://academy.axoniq.io/ https:/ /lp.axoniq.io/devnexus-22 The slides JavaSpecialists newsletter Java Concurrency Specialist Courses