SlideShare une entreprise Scribd logo
@JosePaumard
asynchrones
Java
#J8Async @JosePaumard
Asynchrone ?
#J8Async @JosePaumard
AsynchroneAsynchrone
• Trois tâches à exécuter
T1
T2
T3
#J8Async @JosePaumard
AsynchroneAsynchrone
• 1ère façon de faire :
« exécution synchrone »
#J8Async @JosePaumard
AsynchroneAsynchrone
• 2ème façon de faire :
« exécution multithread »
#J8Async @JosePaumard
AsynchroneAsynchrone
• 2ème façon de faire :
« exécution multithread » … sur un seul cœur
#J8Async @JosePaumard
AsynchroneAsynchrone
• 3ème façon de faire :
« asynchrone »
#J8Async @JosePaumard
AsynchroneAsynchrone
• 3ème façon de faire :
« asynchrone » … même sur un multicœur
#J8Async @JosePaumard
AsynchroneAsynchrone
• 3ème façon de faire :
• Plus rapide ?
#J8Async @JosePaumard
• 3ème façon de faire :
• Plus rapide ?
 En général oui
 Approche « non blocking »
AsynchroneAsynchrone
#J8Async @JosePaumard
• Différence avec le modèle synchrone multithread ?
1) Le traitement décide de passer d’une tâche à l’autre
2) Pas de problème d’atomicité / visibilité
• Performances ?
 Pas de « context switch »
AsynchroneAsynchrone
#J8Async @JosePaumard
• Pattern
AsynchroneAsynchrone
queryEngine.select("select user from User")
.forEach(user ‐> System.out.prinln(user)) ;
#J8Async @JosePaumard
• Pattern
• Callback ou tâche : lambda expression
AsynchroneAsynchrone
queryEngine.select("select user from User")
.forEach(user ‐> System.out.prinln(user)) ;
#J8Async @JosePaumard
• Pattern
• Callback ou tâche : lambda expression
• Enchaînement : lorsque le résultat est disponible
alors on enchaîne avec le traitement
AsynchroneAsynchrone
queryEngine.select("select user from User")
.forEach(System.out::prinln) ;
#J8Async @JosePaumard
• Pattern
• Callback ou tâche : lambda expression
• Enchaînement : lorsque le résultat est disponible
alors on enchaîne avec le traitement
• Comment écrire ceci en Java ?
AsynchroneAsynchrone
queryEngine.select("select user from User")
.forEach(System.out::prinln) ;
#J8Async @JosePaumard
Notion de tâcheNotion de tâche
• Depuis Java 1 : Runnable
• Java 5 : Callable
• Java 5 : ExecutorService (pool de threads)
• On donne une tâche, on récupère un Future
#J8Async @JosePaumard
Notion de tâcheNotion de tâche
• Pattern
Callable<String> task = () ‐> "select user from User" ;
Future<String> future = executorService.submit(task) ;
#J8Async @JosePaumard
Notion de tâcheNotion de tâche
• Pattern
Callable<String> task = () ‐> "select user from User" ;
Future<String> future = executorService.submit(task) ;
List<User> users = future.get() ;    // blocking
users.forEach(System.out::println) ;
#J8Async @JosePaumard
Notion de tâcheNotion de tâche
• Pattern
• Le passage d’un objet d’une tâche à l’autre se fait
dans le thread « maître »
Callable<String> task = () ‐> "select user from User" ;
Future<String> future = executorService.submit(task) ;
List<User> users = future.get() ;    // blocking
users.forEach(System.out::println) ;
#J8Async @JosePaumard
Programmation asynchroneProgrammation asynchrone
• Nouveaux outils en Java 8 pour traiter ce point
• Solution pour enchaîner les tâches
• Asynchrone & multithread
API Asynchrones en Java 8
API Asynchrones en Java 8
API Asynchrones en Java 8
API Asynchrones en Java 8
API Asynchrones en Java 8
#J8Async @JosePaumard
Questions ?
#J8Async
Questions ?
#J8Async
#J8Async @JosePaumard
• Nouvelle interface en Java 8 : CompletionStage
De quoi s’agit-il ?De quoi s’agit-il ?
/**
* A stage of a possibly asynchronous computation, that performs an
* action or computes a value when another CompletionStage completes.
* A stage completes upon termination of its computation, but this may
* in turn trigger other dependent stages.
*/
#J8Async @JosePaumard
• Nouvelle interface en Java 8 : CompletionStage
• CompletionStage = une tâche qui se déclenche sur
une autre et qui peut en déclencher d’autres
De quoi s’agit-il ?De quoi s’agit-il ?
/**
* A stage of a possibly asynchronous computation, that performs an
* action or computes a value when another CompletionStage completes.
* A stage completes upon termination of its computation, but this may
* in turn trigger other dependent stages
*/
#J8Async @JosePaumard
• Classe d’implémentation : CompletableFuture
• Implémente à la fois :
 Future
 CompletionStage
De quoi s’agit-il ?De quoi s’agit-il ?
#J8Async @JosePaumard
• CompletableFuture : modélise une tâche
• Peut être dans trois états :
De quoi s’agit-il ?De quoi s’agit-il ?
#J8Async @JosePaumard
• CompletableFuture : modélise une tâche
• Peut être dans trois états :
 En train d’être calculée
De quoi s’agit-il ?De quoi s’agit-il ?
#J8Async @JosePaumard
• CompletableFuture : modélise une tâche
• Peut être dans trois états :
 En train d’être calculée
 Calculée, ayant produit un résultat
De quoi s’agit-il ?De quoi s’agit-il ?
#J8Async @JosePaumard
• CompletableFuture : modélise une tâche
• Peut être dans trois états :
 En train d’être calculée
 Calculée, ayant produit un résultat
 Calculée, ayant généré une exception
De quoi s’agit-il ?De quoi s’agit-il ?
#J8Async @JosePaumard
FutureFuture
• Cinq méthodes :
boolean cancel(boolean mayInterruptIfRunning) ;
#J8Async @JosePaumard
FutureFuture
• Cinq méthodes :
boolean cancel(boolean mayInterruptIfRunning) ;
boolean isCanceled() ;
boolean isDone() ;
#J8Async @JosePaumard
FutureFuture
• Cinq méthodes :
boolean cancel(boolean mayInterruptIfRunning) ;
boolean isCanceled() ;
boolean isDone() ;
V get() ; // blocking call 
V get(long timeout, TimeUnit timeUnit) ; // may throw a checked exception
throws InterruptedException, ExecutionException, TimeoutException ;
#J8Async @JosePaumard
CompletableFutureCompletableFuture
• Méthodes de type « future » :
V join() ; // may throw an unchecked exception
V getNow(V valueIfAbsent) ; // returns immediately
#J8Async @JosePaumard
CompletableFutureCompletableFuture
• Méthodes de type « future » :
V join() ; // may throw an unchecked exception
V getNow(V valueIfAbsent) ; // returns immediately
boolean complete(V value) ;  // sets the returned value is not returned
void obtrudeValue(V value) ; // resets the returned value 
#J8Async @JosePaumard
CompletableFutureCompletableFuture
• Méthodes de type « future » :
V join() ; // may throw an unchecked exception
V getNow(V valueIfAbsent) ; // returns immediately
boolean complete(V value) ;  // sets the returned value is not returned
void obtrudeValue(V value) ; // resets the returned value 
boolean completeExceptionnaly(Throwable t) ;  // sets an exception
void obtrudeException(Throwable t) ; // resets with an exception
#J8Async @JosePaumard
Création d’un CompletableFutureCréation d’un CompletableFuture
• CompletableFuture déjà terminé
public static <U> CompletableFuture<U> completedFuture(U value) ;
#J8Async @JosePaumard
Création d’un CompletableFutureCréation d’un CompletableFuture
• CompletableFuture déjà terminé
public static <U> CompletableFuture<U> completedFuture(U value) ;
public static <U> CompletableFuture<U> 
supplyAsync(Supplier<U> value, Executor executor) ;
public static <U> CompletableFuture<U> 
runAsync(Runnable runnable, Executor executor) ;
#J8Async @JosePaumard
CompletionStageCompletionStage
• Concept : un étape dans un traitement global
 Peut être déclenchée par une étape précédente
 Peut déclencher d’autres étapes
 Peut être exécutée dans un executor particulier
#J8Async @JosePaumard
CompletionStageCompletionStage
• Notion tâche :
 Function : prend un argument, retourne une valeur
 Consumer : prend un argument
 Runnable
= interfaces fonctionnelles, donc lambda
#J8Async @JosePaumard
CompletionStage – chaînageCompletionStage – chaînage
• Chaînage après, même thread
public <U> CompletionStage<U> 
thenApply(Function<? super T,? extends U> fn);
public CompletionStage<Void> 
thenAccept(Consumer<? super T> action);
public CompletionStage<Void> 
thenRun(Runnable action);
#J8Async @JosePaumard
CompletionStage – chaînageCompletionStage – chaînage
• Chaînage après, autre thread (common FJ pool)
public <U> CompletionStage<U> 
thenApplyAsync(Function<? super T,? extends U> fn);
public CompletionStage<Void> 
thenAcceptAsync(Consumer<? super T> action);
public CompletionStage<Void> 
thenRunAsync(Runnable action);
#J8Async @JosePaumard
CompletionStage – chaînageCompletionStage – chaînage
• Chaînage après, autre thread (executor)
public <U> CompletionStage<U> 
thenApplyAsync(Function<? super T,? extends U> fn, Executor executor);
public CompletionStage<Void> 
thenAcceptAsync(Consumer<? super T> action, Executor executor);
public CompletionStage<Void> 
thenRunAsync(Runnable action, Executor executor);
#J8Async @JosePaumard
CompletionStage – compositionCompletionStage – composition
• Composition
public <U> CompletionStage<U> 
thenCompose(Function<? super T, ? extends CompletionStage<U>> fn);
public CompletionStage<Void> 
thenComposeAsync(
Function<? super T, ? extends CompletionStage<U>> fn);
public CompletionStage<Void> 
thenComposeAsync(
Function<? super T, ? extends CompletionStage<U>> fn,
Executor executor);
#J8Async @JosePaumard
Chaînage & compositionChaînage & composition
• Ces deux familles de fonction permettent d’enchaîner
une opération après l’autre
#J8Async @JosePaumard
Chaînage & compositionChaînage & composition
• On peut aussi enchaîner une tâche à la suite de deux
autres tâches
public CompletionStage<V> thenCombine
(CompletionStage<U> other, 
BiFunction<T, U, V> function) ;
#J8Async @JosePaumard
Chaînage & compositionChaînage & composition
• On peut aussi enchaîner une tâche à la suite de deux
autres tâches
• Prend les résultats de this et other
 Et les combine dans function
public CompletionStage<V> thenCombine
(CompletionStage<U> other, 
BiFunction<T, U, V> function) ;
#J8Async @JosePaumard
Chaînage & compositionChaînage & composition
• On peut aussi enchaîner une tâche à la suite de deux
autres tâches
public CompletionStage<V> thenCombine
(CompletionStage<U> other, 
BiFunction<T, U, V> function) ;
public CompletionStage<V> thenCombineAsync
(CompletionStage<U> other, 
BiFunction<T, U, V> function) ;
#J8Async @JosePaumard
Chaînage & compositionChaînage & composition
• On peut aussi enchaîner une tâche à la suite de deux
autres tâches
public CompletionStage<V> thenCombine
(CompletionStage<U> other, 
BiFunction<T, U, V> function) ;
public CompletionStage<V> thenCombineAsync
(CompletionStage<U> other, 
BiFunction<T, U, V> function, Executor executor) ;
#J8Async @JosePaumard
Chaînage & compositionChaînage & composition
• Versions avec Consumer
public CompletionStage<Void> thenAcceptBoth
(CompletionStage<U> other, 
BiConsumer<T, U> action) ;
public CompletionStage<Void> thenAcceptBothAsync
(CompletionStage<U> other, 
BiConsumer<T, U> action) ;
public CompletionStage<Void> thenAcceptBothAsync
(CompletionStage<U> other, 
BiConsumer<T, U> action, Executor executor) ;
#J8Async @JosePaumard
Chaînage & compositionChaînage & composition
• Versions avec Runnable
public CompletionStage<Void> runAfterBoth
(CompletionStage<?> other, 
Runnable action) ;
public CompletionStage<Void> runAfterBothAsync
(CompletionStage<?> other, 
Runnable action) ;
public CompletionStage<Void> runAfterBothAsync
(CompletionStage<?> other, 
Runnable action, Executor executor) ;
#J8Async @JosePaumard
Chaînage & compositionChaînage & composition
• Ces tâches se déclenchent conditionnellement à this
et à la tâche passée en paramètre
• Lorsque ces tâches sont terminées
• On peut aussi déclencher lorsque la première se
termine
#J8Async @JosePaumard
Chaînage multipleChaînage multiple
• Version function
public CompletionStage<V> applyToEither
(CompletionStage<? extends T> other, 
Function<T, U> function) ;
#J8Async @JosePaumard
Chaînage multipleChaînage multiple
• Version function
public CompletionStage<U> applyToEither
(CompletionStage<? extends T> other, 
Function<T, U> function) ;
public CompletionStage<U> applyToEitherAsync
(CompletionStage<? extends T> other, 
Function<T, U> function) ;
public CompletionStage<U> applyToEitherAsync
(CompletionStage<? extends T> other, 
Function<T, U> function, Executor executor) ;
#J8Async @JosePaumard
Chaînage multipleChaînage multiple
• Version consumer
public CompletionStage<V> acceptEither
(CompletionStage<? extends T> other, 
Consumer<? extends T> consumer) ;
public CompletionStage<V> acceptEitherAsync
(CompletionStage<? extends T> other, 
Consumer<? extends T> consumer) ;
public CompletionStage<V> acceptEitherAsync
(CompletionStage<? extends T> other, 
Consumer<? extends T> consumer, Executor executor) ;
#J8Async @JosePaumard
Chaînage multipleChaînage multiple
• Version runnable
public CompletionStage<V> runAfterEither
(CompletionStage<U> other, 
Runnable action) ;
public CompletionStage<V> runAfterEitherAsync
(CompletionStage<U> other, 
Runnable action) ;
public CompletionStage<V> runAfterEitherAsync
(CompletionStage<U> other, 
Runnable action, Executor executor) ;
#J8Async @JosePaumard
Création sur plusieurs tâchesCréation sur plusieurs tâches
• Méthodes statiques
public static CompletableFuture<Void> 
allOf(CompletableFuture<?>... cfs) ;
public static CompletableFuture<Object> 
anyOf(CompletableFuture<?>... cfs) ;
#J8Async @JosePaumard
Création sur plusieurs tâchesCréation sur plusieurs tâches
• Attention à la sémantique !
• Imprime « null »
public static CompletableFuture<Void> 
allOf(CompletableFuture<?>... cfs) ;
CompletableFuture<Void> allOf = CompletableFuture.allOf() ;
System.out.println("allOF : " + allOf.join()) ;
#J8Async @JosePaumard
Création sur plusieurs tâchesCréation sur plusieurs tâches
• Attention à la sémantique !
• Ne rend pas la main…
public static CompletableFuture<Void> 
allOf(CompletableFuture<?>... cfs) ;
CompletableFuture<Object> anyOf = CompletableFuture.anyOf() ;
System.out.println("anyOf : " + anyOf.join()) ;
#J8Async @JosePaumard
Création sur plusieurs tâchesCréation sur plusieurs tâches
• Attention à la sémantique !
public static CompletableFuture<Void> 
allOf(CompletableFuture<?>... cfs) ;
CompletableFuture<Object> anyOf = CompletableFuture.anyOf() ;
System.out.println("anyOf : " + anyOf.getNow("Nothing to say")) ;
#J8Async @JosePaumard
Gestion des exceptionsGestion des exceptions
• Point délicat :
 Une première étape consiste à créer les tâches et à
décrire leur enchaînement
 L’exécution des tâches démarre indépendamment des
appels
 À chaque étape, un CompletableFuture est créé
#J8Async @JosePaumard
Gestion des exceptionsGestion des exceptions
• Un CompletableFuture peut dépendre :
 Cas 1 : d’un autre CompletableFuture
 Cas 2 : de deux autres CompletableFuture
 Cas 3 : de N CompletableFuture
#J8Async @JosePaumard
Gestion des exceptionsGestion des exceptions
• Une exception est jetée dans le cas 1
 Tous les CompletableFuture sont en erreur
• Ils se terminent « exceptionnellement »
 isExceptionnaly() retourne true
 L’appel à get() jette une ExecutionException
 get().getCause() retourne l’exception première
#J8Async @JosePaumard
Gestion des exceptionsGestion des exceptions
• Une exception est jetée dans le cas 2
 Tous les CompletableFuture en aval sont en erreur
• Ils se terminent « exceptionnellement »
• L’autre tâche peut se terminer normalement
 On peut l’interroger par get() pour avoir son résultat
#J8Async @JosePaumard
Gestion des exceptionsGestion des exceptions
• Une exception est jetée dans le cas 3
 Le CompletableFuture retourné est en erreur
• Il se termine « exceptionnellement »
• Les autres tâches peuvent se terminer normalement
 On peut l’interroger par get() pour avoir son résultat
#J8Async @JosePaumard
Gestion des exceptionsGestion des exceptions
• On peut aussi traiter une exception normalement
 Dans ce cas, l’exception est passée à la fonction
 Utile pour les checked exception
CompletionStage<T> exceptionally(
Function<Throwable, ? extends T> function);
#J8Async @JosePaumard
Gestion des exceptionsGestion des exceptions
• Méthode whenComplete()
 Dans ce cas t ou e est nul dans l’appel de action
 Le CompletableFuture retourné peut ne pas être en
erreur
CompletionStage<T> whenComplete
(BiConsumer<T, Throwable> action) ;
#J8Async @JosePaumard
Gestion des exceptionsGestion des exceptions
• Méthode whenComplete()
CompletionStage<T> whenComplete
(BiConsumer<T, Throwable> action) ;
CompletionStage<T> whenCompleteAsync
(BiConsumer<T, Throwable> action) ;
CompletionStage<T> whenCompleteAsync
(BiConsumer<T, Throwable> action, Executor executor) ;
#J8Async @JosePaumard
Gestion des exceptionsGestion des exceptions
• Méthode handle()
 Dans ce cas t ou e est nul dans l’appel de function
 Retourne un CompletableFuture qui peut ne pas être
en erreur
CompletionStage<T> handle
(BiFunction<T, Throwable, U> function) ;
#J8Async @JosePaumard
Gestion des exceptionsGestion des exceptions
• Méthode handle()
CompletionStage<T> handle
(BiFunction<T, Throwable, U> function) ;
CompletionStage<T> handleAsync
(BiFunction<T, Throwable, U> function) ;
CompletionStage<T> handleAsync
(BiFunction<T, Throwable, U> function, Executor executor) ;
#J8Async @JosePaumard
Une dernière méthodeUne dernière méthode
• CompletableFuture : On peut obtenir une estimation
du nombre de tâches qui attendent l’exécution d’une
tâche donnée
int getNumberOfDependents() ;
#J8Async @JosePaumard
Exemple – 1Exemple – 1
• Lecture asynchrone de liens et affichage
CompletableFuture.supplyAsync(
() ‐> readPage("http://whatever.com/")
)
#J8Async @JosePaumard
Exemple – 1Exemple – 1
• Lecture asynchrone de liens et affichage
CompletableFuture.supplyAsync(
() ‐> readPage("http://whatever.com/")
)
.thenApply(page ‐> linkParser.getLinks(page))
#J8Async @JosePaumard
Exemple – 1Exemple – 1
• Lecture asynchrone de liens et affichage
CompletableFuture.supplyAsync(
() ‐> readPage("http://whatever.com/")
)
.thenApply(page ‐> linkParser.getLinks(page))
.thenAccept(
links ‐> displayPanel.display(links)
) ;
#J8Async @JosePaumard
Exemple – 1Exemple – 1
• Lecture asynchrone de liens et affichage
CompletableFuture.supplyAsync(
() ‐> readPage("http://whatever.com/")
)
.thenApply(page ‐> linkParser.getLinks(page))
.thenAcceptAsync(
links ‐> displayPanel.display(links),
executor
) ;
#J8Async @JosePaumard
Exemple – 1Exemple – 1
• Lecture asynchrone de liens et affichage
public interface Executor {
void execute(Runnable command);
}
#J8Async @JosePaumard
Exemple – 1Exemple – 1
• Lecture asynchrone de liens et affichage
public interface Executor {
void execute(Runnable command);
}
Executor executor = runnable ‐> SwingUtilities.invokeLater(runnable) ;
#J8Async @JosePaumard
Exemple – 1Exemple – 1
• Lecture asynchrone de liens et affichage
CompletableFuture.supplyAsync(
() ‐> readPage("http://whatever.com/")
)
.thenApply(page ‐> linkParser.getLinks(page))
.thenAcceptAsync(
links ‐> displayPanel.display(links), 
runnable ‐> SwingUtilities.invokeLater(runnable)
) ;
#J8Async @JosePaumard
Exemple – 1Exemple – 1
• Lecture asynchrone de liens et affichage
CompletableFuture.supplyAsync(
() ‐> readPage("http://whatever.com/")
)
.thenApply(Parser::getLinks)
.thenAcceptAsync(
DisplayPanel::display, 
SwingUtilities::invokeLater
) ;
#J8Async @JosePaumard
Exemple – 2Exemple – 2
• Événements asynchrones dans CDI
@Inject
Event<String> event ;
event.fire("some event") ; // returns void
public void observes(@Observes String payload) {
// handle the event, called in the firing thread
}
#J8Async @JosePaumard
Exemple – 2Exemple – 2
• Événements asynchrones dans CDI
public void observes(@Observes String payload) {
// handle the event, called in the firing thread
CompletableFuture.anyOf(/* some task */) ;
}
#J8Async @JosePaumard
Exemple – 2Exemple – 2
• Événements asynchrones dans CDI
@Inject
Event<String> event ;
event.fireAsync("some event") ; // returns CompletableFuture<Object> (?)
public void observes(@Observes String payload) {
// handle the event in another thread
}
#J8Async @JosePaumard
Exemple – 2Exemple – 2
• Événements asynchrones dans CDI
@Inject
Event<String> event ;
event.fireAsync("some event", executor) ; 
public void observes(@Observes String payload) {
// handle the event in the executor
}
#J8Async @JosePaumard
Exemple – 2Exemple – 2
• Événements asynchrones dans CDI
@Inject
Event<String> event ;
event.fireAsync("some event", executor) ; 
@Produces @SwingExecutor
Executor executor = SwingUtilities::invokeLater
public void observes(@Observes String payload, 
@SwingExecutor Executor executor) {
// handle the event in the Swing thread
}
#J8Async @JosePaumard
Exemple – 2Exemple – 2
• Événements asynchrones dans CDI
@Inject
Event<String> event ;
event.fireAsync("some event", executor) ; 
@Produces @SwingExecutor
Executor executor = SwingUtilities::invokeLater
public void observes(@Observes @SwingExecutor String payload) {
// handle the event in the Swing thread
}
#J8Async @JosePaumard
Exemple – 3Exemple – 3
CompletableFuture<String> closing = new CompletableFuture<String>() ;
Stream<String> manyStrings = Stream.of("one", "two", "three") ;
CompletableFuture<String> reduce =
manyStrings
.onClose(() ‐> { closing.complete("Closed") ; })
.map(CompletableFuture::completedFuture)
.reduce(
closing,  
(cf1, cf2) ‐> cf1.thenCombine(cf2, function) // concatenation
) ;
manyStrings.close() ;
#J8Async @JosePaumard
L’indispensable !L’indispensable !
• Fixer la taille du Common Fork / Join Pool
System.setProperty(
"java.util.concurrent.ForkJoinPool.common.parallelism", 2) ;
#J8Async @JosePaumard
ConclusionConclusion
• On a une API pour le calcul asynchrone dans le JDK !
#J8Async @JosePaumard
ConclusionConclusion
• On a une API pour le calcul asynchrone dans le JDK !
• Très riche et souple à l’utilisation
#J8Async @JosePaumard
ConclusionConclusion
• On a une API pour le calcul asynchrone dans le JDK !
• Très riche et souple à l’utilisation
• Construite sur l’utilisation des lambda
#J8Async @JosePaumard
ConclusionConclusion
• On a une API pour le calcul asynchrone dans le JDK !
• Très riche et souple à l’utilisation
• Construite sur l’utilisation des lambda
• Permet un contrôle fin des threads
#J8Async @JosePaumard
ConclusionConclusion
• On a une API pour le calcul asynchrone dans le JDK !
• Très riche et souple à l’utilisation
• Construite sur l’utilisation des lambda
• Permet un contrôle fin des threads
• Gère différents types de chaînage
#J8Async @JosePaumard
ConclusionConclusion
• On a une API pour le calcul asynchrone dans le JDK !
• Très riche et souple à l’utilisation
• Construite sur l’utilisation des lambda
• Permet un contrôle fin des threads
• Gère différents types de chaînage
• Gère intelligemment les exceptions
@JosePaumard#J8Stream
@JosePaumard#J8Stream
Publicité

Contenu connexe

Tendances (20)

Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
Harshit Choudhary
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Edureka!
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
07.pallav
 
Nouveautés Java 9-10-11
Nouveautés Java 9-10-11Nouveautés Java 9-10-11
Nouveautés Java 9-10-11
Mahamadou TOURE, Ph.D.
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Spring Boot
Spring BootSpring Boot
Spring Boot
HongSeong Jeon
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
Akshay Mathur
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017
Roman Elizarov
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Spring Batch 2.0
Spring Batch 2.0Spring Batch 2.0
Spring Batch 2.0
Guido Schmutz
 
Java 11 to 17 : What's new !?
Java 11 to 17 : What's new !?Java 11 to 17 : What's new !?
Java 11 to 17 : What's new !?
Jérôme Tamborini
 
POO Java Chapitre 6 Exceptions
POO Java  Chapitre 6 ExceptionsPOO Java  Chapitre 6 Exceptions
POO Java Chapitre 6 Exceptions
Mouna Torjmen
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Spring boot
Spring bootSpring boot
Spring boot
sdeeg
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
Antoine Rey
 
Cours design pattern m youssfi partie 5 adapter
Cours design pattern m youssfi partie 5 adapterCours design pattern m youssfi partie 5 adapter
Cours design pattern m youssfi partie 5 adapter
ENSET, Université Hassan II Casablanca
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
Richard Paul
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
Eberhard Wolff
 
Spring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'tsSpring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'ts
Julien Wittouck
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Edureka!
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
07.pallav
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
Akshay Mathur
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017
Roman Elizarov
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
POO Java Chapitre 6 Exceptions
POO Java  Chapitre 6 ExceptionsPOO Java  Chapitre 6 Exceptions
POO Java Chapitre 6 Exceptions
Mouna Torjmen
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Spring boot
Spring bootSpring boot
Spring boot
sdeeg
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
Antoine Rey
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
Richard Paul
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
Eberhard Wolff
 
Spring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'tsSpring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'ts
Julien Wittouck
 

En vedette (6)

Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nous
José Paumard
 
Quoi de neuf à Devoxx France 2017 ?
Quoi de neuf à Devoxx France 2017 ?Quoi de neuf à Devoxx France 2017 ?
Quoi de neuf à Devoxx France 2017 ?
Antoine Rey
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
Antoine Rey
 
Autumn collection JavaOne 2014
Autumn collection JavaOne 2014Autumn collection JavaOne 2014
Autumn collection JavaOne 2014
José Paumard
 
50 new things you can do with java 8
50 new things you can do with java 850 new things you can do with java 8
50 new things you can do with java 8
José Paumard
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nous
José Paumard
 
Quoi de neuf à Devoxx France 2017 ?
Quoi de neuf à Devoxx France 2017 ?Quoi de neuf à Devoxx France 2017 ?
Quoi de neuf à Devoxx France 2017 ?
Antoine Rey
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
Antoine Rey
 
Autumn collection JavaOne 2014
Autumn collection JavaOne 2014Autumn collection JavaOne 2014
Autumn collection JavaOne 2014
José Paumard
 
50 new things you can do with java 8
50 new things you can do with java 850 new things you can do with java 8
50 new things you can do with java 8
José Paumard
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Publicité

Similaire à API Asynchrones en Java 8 (20)

Living Documentation (TDD, BDD).pptx
Living Documentation (TDD, BDD).pptxLiving Documentation (TDD, BDD).pptx
Living Documentation (TDD, BDD).pptx
Guillaume Saint Etienne
 
16-Concurrence-APIs-Concurrentes.pdf
16-Concurrence-APIs-Concurrentes.pdf16-Concurrence-APIs-Concurrentes.pdf
16-Concurrence-APIs-Concurrentes.pdf
Patiento Del Mar
 
Backday xebia - Chercher la performance efficacement
Backday xebia - Chercher la performance efficacement Backday xebia - Chercher la performance efficacement
Backday xebia - Chercher la performance efficacement
Publicis Sapient Engineering
 
Patterns et bonnes pratiques autour de JavaScript
Patterns et bonnes pratiques autour de JavaScriptPatterns et bonnes pratiques autour de JavaScript
Patterns et bonnes pratiques autour de JavaScript
Microsoft Technet France
 
Future of java script web version
Future of java script web versionFuture of java script web version
Future of java script web version
Sébastien Pertus
 
Gatling Tool in Action at DevoxxFR 2012
Gatling Tool in Action at DevoxxFR 2012Gatling Tool in Action at DevoxxFR 2012
Gatling Tool in Action at DevoxxFR 2012
slandelle
 
Javascript - Fonctions : que fait ce code ?
Javascript - Fonctions : que fait ce code ?Javascript - Fonctions : que fait ce code ?
Javascript - Fonctions : que fait ce code ?
Ruau Mickael
 
C# et .NET : Enigmes et puzzles
C# et .NET : Enigmes  et puzzlesC# et .NET : Enigmes  et puzzles
C# et .NET : Enigmes et puzzles
Microsoft
 
Automatiser les tests d'acceptation : comment s'y prendre ?
Automatiser les tests d'acceptation : comment s'y prendre ?Automatiser les tests d'acceptation : comment s'y prendre ?
Automatiser les tests d'acceptation : comment s'y prendre ?
Vincent Tencé
 
Automatiser les tests d’acceptation : comment s’y prendre ? - Vincent Tencé
Automatiser les tests d’acceptation : comment s’y prendre ? - Vincent TencéAutomatiser les tests d’acceptation : comment s’y prendre ? - Vincent Tencé
Automatiser les tests d’acceptation : comment s’y prendre ? - Vincent Tencé
Agile Montréal
 
Function oop - bonnes pratiques ms tech days
Function   oop - bonnes pratiques ms tech daysFunction   oop - bonnes pratiques ms tech days
Function oop - bonnes pratiques ms tech days
Jean-Pierre Vincent
 
Paris JUG Spring Batch
Paris JUG Spring BatchParis JUG Spring Batch
Paris JUG Spring Batch
Olivier BAZOUD
 
Asyncio: offrez des tulipes à vos entrées sorties asynchrones
Asyncio: offrez des tulipes à vos entrées sorties asynchronesAsyncio: offrez des tulipes à vos entrées sorties asynchrones
Asyncio: offrez des tulipes à vos entrées sorties asynchrones
tchappui
 
Introduction à JavaScript
Introduction à JavaScriptIntroduction à JavaScript
Introduction à JavaScript
Microsoft
 
Spring Batch 17-05-2011
Spring Batch 17-05-2011Spring Batch 17-05-2011
Spring Batch 17-05-2011
Normandy JUG
 
Promises Javascript
Promises JavascriptPromises Javascript
Promises Javascript
Julien CROUZET
 
Nouveautés JavaScript dans le monde Microsoft
Nouveautés JavaScript dans le monde MicrosoftNouveautés JavaScript dans le monde Microsoft
Nouveautés JavaScript dans le monde Microsoft
davrous
 
Plpython et Triggers
Plpython et TriggersPlpython et Triggers
Plpython et Triggers
Affinitic
 
tp-developpement-digital-opt-applications-mobiles-m207-27-04-2023-64624d69394...
tp-developpement-digital-opt-applications-mobiles-m207-27-04-2023-64624d69394...tp-developpement-digital-opt-applications-mobiles-m207-27-04-2023-64624d69394...
tp-developpement-digital-opt-applications-mobiles-m207-27-04-2023-64624d69394...
LebizTheOne
 
16-Concurrence-APIs-Concurrentes.pdf
16-Concurrence-APIs-Concurrentes.pdf16-Concurrence-APIs-Concurrentes.pdf
16-Concurrence-APIs-Concurrentes.pdf
Patiento Del Mar
 
Backday xebia - Chercher la performance efficacement
Backday xebia - Chercher la performance efficacement Backday xebia - Chercher la performance efficacement
Backday xebia - Chercher la performance efficacement
Publicis Sapient Engineering
 
Patterns et bonnes pratiques autour de JavaScript
Patterns et bonnes pratiques autour de JavaScriptPatterns et bonnes pratiques autour de JavaScript
Patterns et bonnes pratiques autour de JavaScript
Microsoft Technet France
 
Future of java script web version
Future of java script web versionFuture of java script web version
Future of java script web version
Sébastien Pertus
 
Gatling Tool in Action at DevoxxFR 2012
Gatling Tool in Action at DevoxxFR 2012Gatling Tool in Action at DevoxxFR 2012
Gatling Tool in Action at DevoxxFR 2012
slandelle
 
Javascript - Fonctions : que fait ce code ?
Javascript - Fonctions : que fait ce code ?Javascript - Fonctions : que fait ce code ?
Javascript - Fonctions : que fait ce code ?
Ruau Mickael
 
C# et .NET : Enigmes et puzzles
C# et .NET : Enigmes  et puzzlesC# et .NET : Enigmes  et puzzles
C# et .NET : Enigmes et puzzles
Microsoft
 
Automatiser les tests d'acceptation : comment s'y prendre ?
Automatiser les tests d'acceptation : comment s'y prendre ?Automatiser les tests d'acceptation : comment s'y prendre ?
Automatiser les tests d'acceptation : comment s'y prendre ?
Vincent Tencé
 
Automatiser les tests d’acceptation : comment s’y prendre ? - Vincent Tencé
Automatiser les tests d’acceptation : comment s’y prendre ? - Vincent TencéAutomatiser les tests d’acceptation : comment s’y prendre ? - Vincent Tencé
Automatiser les tests d’acceptation : comment s’y prendre ? - Vincent Tencé
Agile Montréal
 
Function oop - bonnes pratiques ms tech days
Function   oop - bonnes pratiques ms tech daysFunction   oop - bonnes pratiques ms tech days
Function oop - bonnes pratiques ms tech days
Jean-Pierre Vincent
 
Paris JUG Spring Batch
Paris JUG Spring BatchParis JUG Spring Batch
Paris JUG Spring Batch
Olivier BAZOUD
 
Asyncio: offrez des tulipes à vos entrées sorties asynchrones
Asyncio: offrez des tulipes à vos entrées sorties asynchronesAsyncio: offrez des tulipes à vos entrées sorties asynchrones
Asyncio: offrez des tulipes à vos entrées sorties asynchrones
tchappui
 
Introduction à JavaScript
Introduction à JavaScriptIntroduction à JavaScript
Introduction à JavaScript
Microsoft
 
Spring Batch 17-05-2011
Spring Batch 17-05-2011Spring Batch 17-05-2011
Spring Batch 17-05-2011
Normandy JUG
 
Nouveautés JavaScript dans le monde Microsoft
Nouveautés JavaScript dans le monde MicrosoftNouveautés JavaScript dans le monde Microsoft
Nouveautés JavaScript dans le monde Microsoft
davrous
 
Plpython et Triggers
Plpython et TriggersPlpython et Triggers
Plpython et Triggers
Affinitic
 
tp-developpement-digital-opt-applications-mobiles-m207-27-04-2023-64624d69394...
tp-developpement-digital-opt-applications-mobiles-m207-27-04-2023-64624d69394...tp-developpement-digital-opt-applications-mobiles-m207-27-04-2023-64624d69394...
tp-developpement-digital-opt-applications-mobiles-m207-27-04-2023-64624d69394...
LebizTheOne
 
Publicité

Plus de José Paumard (20)

Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19
José Paumard
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdf
José Paumard
 
The Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingThe Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern Matching
José Paumard
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
José Paumard
 
Designing functional and fluent API: application to some GoF patterns
Designing functional and fluent API: application to some GoF patternsDesigning functional and fluent API: application to some GoF patterns
Designing functional and fluent API: application to some GoF patterns
José Paumard
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
José Paumard
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
José Paumard
 
Designing functional and fluent API: example of the Visitor Pattern
Designing functional and fluent API: example of the Visitor PatternDesigning functional and fluent API: example of the Visitor Pattern
Designing functional and fluent API: example of the Visitor Pattern
José Paumard
 
Construire son JDK en 10 étapes
Construire son JDK en 10 étapesConstruire son JDK en 10 étapes
Construire son JDK en 10 étapes
José Paumard
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
José Paumard
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
José Paumard
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
José Paumard
 
Asynchronous Systems with Fn Flow
Asynchronous Systems with Fn FlowAsynchronous Systems with Fn Flow
Asynchronous Systems with Fn Flow
José Paumard
 
Java Full Throttle
Java Full ThrottleJava Full Throttle
Java Full Throttle
José Paumard
 
JAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) BridgeJAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) Bridge
José Paumard
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
José Paumard
 
Streams in the wild
Streams in the wildStreams in the wild
Streams in the wild
José Paumard
 
JAX RS and CDI bike the reactive bridge
JAX RS and CDI bike the reactive bridgeJAX RS and CDI bike the reactive bridge
JAX RS and CDI bike the reactive bridge
José Paumard
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
José Paumard
 
Linked to ArrayList: the full story
Linked to ArrayList: the full storyLinked to ArrayList: the full story
Linked to ArrayList: the full story
José Paumard
 
Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19
José Paumard
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdf
José Paumard
 
The Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingThe Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern Matching
José Paumard
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
José Paumard
 
Designing functional and fluent API: application to some GoF patterns
Designing functional and fluent API: application to some GoF patternsDesigning functional and fluent API: application to some GoF patterns
Designing functional and fluent API: application to some GoF patterns
José Paumard
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
José Paumard
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
José Paumard
 
Designing functional and fluent API: example of the Visitor Pattern
Designing functional and fluent API: example of the Visitor PatternDesigning functional and fluent API: example of the Visitor Pattern
Designing functional and fluent API: example of the Visitor Pattern
José Paumard
 
Construire son JDK en 10 étapes
Construire son JDK en 10 étapesConstruire son JDK en 10 étapes
Construire son JDK en 10 étapes
José Paumard
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
José Paumard
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
José Paumard
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
José Paumard
 
Asynchronous Systems with Fn Flow
Asynchronous Systems with Fn FlowAsynchronous Systems with Fn Flow
Asynchronous Systems with Fn Flow
José Paumard
 
JAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) BridgeJAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) Bridge
José Paumard
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
José Paumard
 
JAX RS and CDI bike the reactive bridge
JAX RS and CDI bike the reactive bridgeJAX RS and CDI bike the reactive bridge
JAX RS and CDI bike the reactive bridge
José Paumard
 
Linked to ArrayList: the full story
Linked to ArrayList: the full storyLinked to ArrayList: the full story
Linked to ArrayList: the full story
José Paumard
 

Dernier (20)

Group Dynamics for Teams 5th Edition Levi Test Bank
Group Dynamics for Teams 5th Edition Levi Test BankGroup Dynamics for Teams 5th Edition Levi Test Bank
Group Dynamics for Teams 5th Edition Levi Test Bank
pittihalindx
 
Learning concurrent programming in Scala learn the art of building intricate ...
Learning concurrent programming in Scala learn the art of building intricate ...Learning concurrent programming in Scala learn the art of building intricate ...
Learning concurrent programming in Scala learn the art of building intricate ...
hinalkijak1l
 
ISO 22000-HACCP Presentation HAMMANI BACHIR .pptx
ISO 22000-HACCP Presentation HAMMANI BACHIR .pptxISO 22000-HACCP Presentation HAMMANI BACHIR .pptx
ISO 22000-HACCP Presentation HAMMANI BACHIR .pptx
ssuser6d4314
 
cataracte.pdfqwfhoqwhfohncohqwefiowqfknq
cataracte.pdfqwfhoqwhfohncohqwefiowqfknqcataracte.pdfqwfhoqwhfohncohqwefiowqfknq
cataracte.pdfqwfhoqwhfohncohqwefiowqfknq
hpothmanelmn
 
Texas Politics Today 2015 2016 Edition 17th Edition Maxwell Test Bank
Texas Politics Today 2015 2016 Edition 17th Edition Maxwell Test BankTexas Politics Today 2015 2016 Edition 17th Edition Maxwell Test Bank
Texas Politics Today 2015 2016 Edition 17th Edition Maxwell Test Bank
fadhelhaziri
 
Solution Manual for Accounting for Governmental & Nonprofit Entities, 19th Ed...
Solution Manual for Accounting for Governmental & Nonprofit Entities, 19th Ed...Solution Manual for Accounting for Governmental & Nonprofit Entities, 19th Ed...
Solution Manual for Accounting for Governmental & Nonprofit Entities, 19th Ed...
seritmribai
 
Jeux de rôle pour les formateurs Proust et Boutros.pdf
Jeux de rôle pour les formateurs Proust et Boutros.pdfJeux de rôle pour les formateurs Proust et Boutros.pdf
Jeux de rôle pour les formateurs Proust et Boutros.pdf
Amina CHEROUANA
 
🎤 Grand oral - Et si vous pouviez improviser n'importe quel discours avec con...
🎤 Grand oral - Et si vous pouviez improviser n'importe quel discours avec con...🎤 Grand oral - Et si vous pouviez improviser n'importe quel discours avec con...
🎤 Grand oral - Et si vous pouviez improviser n'importe quel discours avec con...
Miguel Delamontagne
 
🎤 Grand Oral - Le Jury Peut-Il Remettre en Cause la Question ? - FAQ 29
🎤 Grand Oral - Le Jury Peut-Il Remettre en Cause la Question ? - FAQ 29🎤 Grand Oral - Le Jury Peut-Il Remettre en Cause la Question ? - FAQ 29
🎤 Grand Oral - Le Jury Peut-Il Remettre en Cause la Question ? - FAQ 29
Miguel Delamontagne
 
Marketing Real People Real Choices 9th Edition Solomon Test Bank
Marketing Real People Real Choices 9th Edition Solomon Test BankMarketing Real People Real Choices 9th Edition Solomon Test Bank
Marketing Real People Real Choices 9th Edition Solomon Test Bank
grubecovarxq
 
MultiMedia Modeling 23rd International Conference MMM 2017 Reykjavik Iceland ...
MultiMedia Modeling 23rd International Conference MMM 2017 Reykjavik Iceland ...MultiMedia Modeling 23rd International Conference MMM 2017 Reykjavik Iceland ...
MultiMedia Modeling 23rd International Conference MMM 2017 Reykjavik Iceland ...
rhodaeickeat
 
Hernie de l'aine^J ombilicale(Updated).pdf
Hernie de l'aine^J ombilicale(Updated).pdfHernie de l'aine^J ombilicale(Updated).pdf
Hernie de l'aine^J ombilicale(Updated).pdf
theachanrith2099
 
🎤 Grand oral - Votre arme secrète pour briller au Grand Oral - 3/17
🎤 Grand oral - Votre arme secrète pour briller au Grand Oral - 3/17🎤 Grand oral - Votre arme secrète pour briller au Grand Oral - 3/17
🎤 Grand oral - Votre arme secrète pour briller au Grand Oral - 3/17
Miguel Delamontagne
 
Présentation orale 02 : "Les vacances 2025"
Présentation orale 02 : "Les vacances 2025"Présentation orale 02 : "Les vacances 2025"
Présentation orale 02 : "Les vacances 2025"
RedWingates
 
Cours sur Introduction à SQL Alchemy.pptx
Cours sur Introduction à SQL Alchemy.pptxCours sur Introduction à SQL Alchemy.pptx
Cours sur Introduction à SQL Alchemy.pptx
SayobaGansane
 
Compounds of Uranium and Fluorine Chemical Compounds 1st Edition Christopher ...
Compounds of Uranium and Fluorine Chemical Compounds 1st Edition Christopher ...Compounds of Uranium and Fluorine Chemical Compounds 1st Edition Christopher ...
Compounds of Uranium and Fluorine Chemical Compounds 1st Edition Christopher ...
shirkamiahlp
 
🎤 Grand oral - Et si votre spontanéité devenait votre plus grande force au...
🎤 Grand oral  -   Et si votre spontanéité devenait votre plus grande force au...🎤 Grand oral  -   Et si votre spontanéité devenait votre plus grande force au...
🎤 Grand oral - Et si votre spontanéité devenait votre plus grande force au...
Miguel Delamontagne
 
Microsoft Access 2013 Comprehensive 1st Edition Pratt Test Bank
Microsoft Access 2013 Comprehensive 1st Edition Pratt Test BankMicrosoft Access 2013 Comprehensive 1st Edition Pratt Test Bank
Microsoft Access 2013 Comprehensive 1st Edition Pratt Test Bank
forsthazer79
 
Nursing Delegation and Management of Patient Care 2nd Edition Motacki Test Bank
Nursing Delegation and Management of Patient Care 2nd Edition Motacki Test BankNursing Delegation and Management of Patient Care 2nd Edition Motacki Test Bank
Nursing Delegation and Management of Patient Care 2nd Edition Motacki Test Bank
maniapurickul
 
Antimicrobial Food Packaging 1st Edition Barros-Velazquez
Antimicrobial Food Packaging 1st Edition Barros-VelazquezAntimicrobial Food Packaging 1st Edition Barros-Velazquez
Antimicrobial Food Packaging 1st Edition Barros-Velazquez
aycoxsonkavv
 
Group Dynamics for Teams 5th Edition Levi Test Bank
Group Dynamics for Teams 5th Edition Levi Test BankGroup Dynamics for Teams 5th Edition Levi Test Bank
Group Dynamics for Teams 5th Edition Levi Test Bank
pittihalindx
 
Learning concurrent programming in Scala learn the art of building intricate ...
Learning concurrent programming in Scala learn the art of building intricate ...Learning concurrent programming in Scala learn the art of building intricate ...
Learning concurrent programming in Scala learn the art of building intricate ...
hinalkijak1l
 
ISO 22000-HACCP Presentation HAMMANI BACHIR .pptx
ISO 22000-HACCP Presentation HAMMANI BACHIR .pptxISO 22000-HACCP Presentation HAMMANI BACHIR .pptx
ISO 22000-HACCP Presentation HAMMANI BACHIR .pptx
ssuser6d4314
 
cataracte.pdfqwfhoqwhfohncohqwefiowqfknq
cataracte.pdfqwfhoqwhfohncohqwefiowqfknqcataracte.pdfqwfhoqwhfohncohqwefiowqfknq
cataracte.pdfqwfhoqwhfohncohqwefiowqfknq
hpothmanelmn
 
Texas Politics Today 2015 2016 Edition 17th Edition Maxwell Test Bank
Texas Politics Today 2015 2016 Edition 17th Edition Maxwell Test BankTexas Politics Today 2015 2016 Edition 17th Edition Maxwell Test Bank
Texas Politics Today 2015 2016 Edition 17th Edition Maxwell Test Bank
fadhelhaziri
 
Solution Manual for Accounting for Governmental & Nonprofit Entities, 19th Ed...
Solution Manual for Accounting for Governmental & Nonprofit Entities, 19th Ed...Solution Manual for Accounting for Governmental & Nonprofit Entities, 19th Ed...
Solution Manual for Accounting for Governmental & Nonprofit Entities, 19th Ed...
seritmribai
 
Jeux de rôle pour les formateurs Proust et Boutros.pdf
Jeux de rôle pour les formateurs Proust et Boutros.pdfJeux de rôle pour les formateurs Proust et Boutros.pdf
Jeux de rôle pour les formateurs Proust et Boutros.pdf
Amina CHEROUANA
 
🎤 Grand oral - Et si vous pouviez improviser n'importe quel discours avec con...
🎤 Grand oral - Et si vous pouviez improviser n'importe quel discours avec con...🎤 Grand oral - Et si vous pouviez improviser n'importe quel discours avec con...
🎤 Grand oral - Et si vous pouviez improviser n'importe quel discours avec con...
Miguel Delamontagne
 
🎤 Grand Oral - Le Jury Peut-Il Remettre en Cause la Question ? - FAQ 29
🎤 Grand Oral - Le Jury Peut-Il Remettre en Cause la Question ? - FAQ 29🎤 Grand Oral - Le Jury Peut-Il Remettre en Cause la Question ? - FAQ 29
🎤 Grand Oral - Le Jury Peut-Il Remettre en Cause la Question ? - FAQ 29
Miguel Delamontagne
 
Marketing Real People Real Choices 9th Edition Solomon Test Bank
Marketing Real People Real Choices 9th Edition Solomon Test BankMarketing Real People Real Choices 9th Edition Solomon Test Bank
Marketing Real People Real Choices 9th Edition Solomon Test Bank
grubecovarxq
 
MultiMedia Modeling 23rd International Conference MMM 2017 Reykjavik Iceland ...
MultiMedia Modeling 23rd International Conference MMM 2017 Reykjavik Iceland ...MultiMedia Modeling 23rd International Conference MMM 2017 Reykjavik Iceland ...
MultiMedia Modeling 23rd International Conference MMM 2017 Reykjavik Iceland ...
rhodaeickeat
 
Hernie de l'aine^J ombilicale(Updated).pdf
Hernie de l'aine^J ombilicale(Updated).pdfHernie de l'aine^J ombilicale(Updated).pdf
Hernie de l'aine^J ombilicale(Updated).pdf
theachanrith2099
 
🎤 Grand oral - Votre arme secrète pour briller au Grand Oral - 3/17
🎤 Grand oral - Votre arme secrète pour briller au Grand Oral - 3/17🎤 Grand oral - Votre arme secrète pour briller au Grand Oral - 3/17
🎤 Grand oral - Votre arme secrète pour briller au Grand Oral - 3/17
Miguel Delamontagne
 
Présentation orale 02 : "Les vacances 2025"
Présentation orale 02 : "Les vacances 2025"Présentation orale 02 : "Les vacances 2025"
Présentation orale 02 : "Les vacances 2025"
RedWingates
 
Cours sur Introduction à SQL Alchemy.pptx
Cours sur Introduction à SQL Alchemy.pptxCours sur Introduction à SQL Alchemy.pptx
Cours sur Introduction à SQL Alchemy.pptx
SayobaGansane
 
Compounds of Uranium and Fluorine Chemical Compounds 1st Edition Christopher ...
Compounds of Uranium and Fluorine Chemical Compounds 1st Edition Christopher ...Compounds of Uranium and Fluorine Chemical Compounds 1st Edition Christopher ...
Compounds of Uranium and Fluorine Chemical Compounds 1st Edition Christopher ...
shirkamiahlp
 
🎤 Grand oral - Et si votre spontanéité devenait votre plus grande force au...
🎤 Grand oral  -   Et si votre spontanéité devenait votre plus grande force au...🎤 Grand oral  -   Et si votre spontanéité devenait votre plus grande force au...
🎤 Grand oral - Et si votre spontanéité devenait votre plus grande force au...
Miguel Delamontagne
 
Microsoft Access 2013 Comprehensive 1st Edition Pratt Test Bank
Microsoft Access 2013 Comprehensive 1st Edition Pratt Test BankMicrosoft Access 2013 Comprehensive 1st Edition Pratt Test Bank
Microsoft Access 2013 Comprehensive 1st Edition Pratt Test Bank
forsthazer79
 
Nursing Delegation and Management of Patient Care 2nd Edition Motacki Test Bank
Nursing Delegation and Management of Patient Care 2nd Edition Motacki Test BankNursing Delegation and Management of Patient Care 2nd Edition Motacki Test Bank
Nursing Delegation and Management of Patient Care 2nd Edition Motacki Test Bank
maniapurickul
 
Antimicrobial Food Packaging 1st Edition Barros-Velazquez
Antimicrobial Food Packaging 1st Edition Barros-VelazquezAntimicrobial Food Packaging 1st Edition Barros-Velazquez
Antimicrobial Food Packaging 1st Edition Barros-Velazquez
aycoxsonkavv
 

API Asynchrones en Java 8

  • 4. #J8Async @JosePaumard AsynchroneAsynchrone • 1ère façon de faire : « exécution synchrone »
  • 5. #J8Async @JosePaumard AsynchroneAsynchrone • 2ème façon de faire : « exécution multithread »
  • 6. #J8Async @JosePaumard AsynchroneAsynchrone • 2ème façon de faire : « exécution multithread » … sur un seul cœur
  • 7. #J8Async @JosePaumard AsynchroneAsynchrone • 3ème façon de faire : « asynchrone »
  • 8. #J8Async @JosePaumard AsynchroneAsynchrone • 3ème façon de faire : « asynchrone » … même sur un multicœur
  • 9. #J8Async @JosePaumard AsynchroneAsynchrone • 3ème façon de faire : • Plus rapide ?
  • 10. #J8Async @JosePaumard • 3ème façon de faire : • Plus rapide ?  En général oui  Approche « non blocking » AsynchroneAsynchrone
  • 11. #J8Async @JosePaumard • Différence avec le modèle synchrone multithread ? 1) Le traitement décide de passer d’une tâche à l’autre 2) Pas de problème d’atomicité / visibilité • Performances ?  Pas de « context switch » AsynchroneAsynchrone
  • 13. #J8Async @JosePaumard • Pattern • Callback ou tâche : lambda expression AsynchroneAsynchrone queryEngine.select("select user from User") .forEach(user ‐> System.out.prinln(user)) ;
  • 14. #J8Async @JosePaumard • Pattern • Callback ou tâche : lambda expression • Enchaînement : lorsque le résultat est disponible alors on enchaîne avec le traitement AsynchroneAsynchrone queryEngine.select("select user from User") .forEach(System.out::prinln) ;
  • 15. #J8Async @JosePaumard • Pattern • Callback ou tâche : lambda expression • Enchaînement : lorsque le résultat est disponible alors on enchaîne avec le traitement • Comment écrire ceci en Java ? AsynchroneAsynchrone queryEngine.select("select user from User") .forEach(System.out::prinln) ;
  • 16. #J8Async @JosePaumard Notion de tâcheNotion de tâche • Depuis Java 1 : Runnable • Java 5 : Callable • Java 5 : ExecutorService (pool de threads) • On donne une tâche, on récupère un Future
  • 17. #J8Async @JosePaumard Notion de tâcheNotion de tâche • Pattern Callable<String> task = () ‐> "select user from User" ; Future<String> future = executorService.submit(task) ;
  • 18. #J8Async @JosePaumard Notion de tâcheNotion de tâche • Pattern Callable<String> task = () ‐> "select user from User" ; Future<String> future = executorService.submit(task) ; List<User> users = future.get() ;    // blocking users.forEach(System.out::println) ;
  • 19. #J8Async @JosePaumard Notion de tâcheNotion de tâche • Pattern • Le passage d’un objet d’une tâche à l’autre se fait dans le thread « maître » Callable<String> task = () ‐> "select user from User" ; Future<String> future = executorService.submit(task) ; List<User> users = future.get() ;    // blocking users.forEach(System.out::println) ;
  • 20. #J8Async @JosePaumard Programmation asynchroneProgrammation asynchrone • Nouveaux outils en Java 8 pour traiter ce point • Solution pour enchaîner les tâches • Asynchrone & multithread
  • 27. #J8Async @JosePaumard • Nouvelle interface en Java 8 : CompletionStage De quoi s’agit-il ?De quoi s’agit-il ? /** * A stage of a possibly asynchronous computation, that performs an * action or computes a value when another CompletionStage completes. * A stage completes upon termination of its computation, but this may * in turn trigger other dependent stages. */
  • 28. #J8Async @JosePaumard • Nouvelle interface en Java 8 : CompletionStage • CompletionStage = une tâche qui se déclenche sur une autre et qui peut en déclencher d’autres De quoi s’agit-il ?De quoi s’agit-il ? /** * A stage of a possibly asynchronous computation, that performs an * action or computes a value when another CompletionStage completes. * A stage completes upon termination of its computation, but this may * in turn trigger other dependent stages */
  • 29. #J8Async @JosePaumard • Classe d’implémentation : CompletableFuture • Implémente à la fois :  Future  CompletionStage De quoi s’agit-il ?De quoi s’agit-il ?
  • 30. #J8Async @JosePaumard • CompletableFuture : modélise une tâche • Peut être dans trois états : De quoi s’agit-il ?De quoi s’agit-il ?
  • 31. #J8Async @JosePaumard • CompletableFuture : modélise une tâche • Peut être dans trois états :  En train d’être calculée De quoi s’agit-il ?De quoi s’agit-il ?
  • 32. #J8Async @JosePaumard • CompletableFuture : modélise une tâche • Peut être dans trois états :  En train d’être calculée  Calculée, ayant produit un résultat De quoi s’agit-il ?De quoi s’agit-il ?
  • 33. #J8Async @JosePaumard • CompletableFuture : modélise une tâche • Peut être dans trois états :  En train d’être calculée  Calculée, ayant produit un résultat  Calculée, ayant généré une exception De quoi s’agit-il ?De quoi s’agit-il ?
  • 34. #J8Async @JosePaumard FutureFuture • Cinq méthodes : boolean cancel(boolean mayInterruptIfRunning) ;
  • 35. #J8Async @JosePaumard FutureFuture • Cinq méthodes : boolean cancel(boolean mayInterruptIfRunning) ; boolean isCanceled() ; boolean isDone() ;
  • 36. #J8Async @JosePaumard FutureFuture • Cinq méthodes : boolean cancel(boolean mayInterruptIfRunning) ; boolean isCanceled() ; boolean isDone() ; V get() ; // blocking call  V get(long timeout, TimeUnit timeUnit) ; // may throw a checked exception throws InterruptedException, ExecutionException, TimeoutException ;
  • 37. #J8Async @JosePaumard CompletableFutureCompletableFuture • Méthodes de type « future » : V join() ; // may throw an unchecked exception V getNow(V valueIfAbsent) ; // returns immediately
  • 38. #J8Async @JosePaumard CompletableFutureCompletableFuture • Méthodes de type « future » : V join() ; // may throw an unchecked exception V getNow(V valueIfAbsent) ; // returns immediately boolean complete(V value) ;  // sets the returned value is not returned void obtrudeValue(V value) ; // resets the returned value 
  • 39. #J8Async @JosePaumard CompletableFutureCompletableFuture • Méthodes de type « future » : V join() ; // may throw an unchecked exception V getNow(V valueIfAbsent) ; // returns immediately boolean complete(V value) ;  // sets the returned value is not returned void obtrudeValue(V value) ; // resets the returned value  boolean completeExceptionnaly(Throwable t) ;  // sets an exception void obtrudeException(Throwable t) ; // resets with an exception
  • 40. #J8Async @JosePaumard Création d’un CompletableFutureCréation d’un CompletableFuture • CompletableFuture déjà terminé public static <U> CompletableFuture<U> completedFuture(U value) ;
  • 41. #J8Async @JosePaumard Création d’un CompletableFutureCréation d’un CompletableFuture • CompletableFuture déjà terminé public static <U> CompletableFuture<U> completedFuture(U value) ; public static <U> CompletableFuture<U>  supplyAsync(Supplier<U> value, Executor executor) ; public static <U> CompletableFuture<U>  runAsync(Runnable runnable, Executor executor) ;
  • 42. #J8Async @JosePaumard CompletionStageCompletionStage • Concept : un étape dans un traitement global  Peut être déclenchée par une étape précédente  Peut déclencher d’autres étapes  Peut être exécutée dans un executor particulier
  • 43. #J8Async @JosePaumard CompletionStageCompletionStage • Notion tâche :  Function : prend un argument, retourne une valeur  Consumer : prend un argument  Runnable = interfaces fonctionnelles, donc lambda
  • 44. #J8Async @JosePaumard CompletionStage – chaînageCompletionStage – chaînage • Chaînage après, même thread public <U> CompletionStage<U>  thenApply(Function<? super T,? extends U> fn); public CompletionStage<Void>  thenAccept(Consumer<? super T> action); public CompletionStage<Void>  thenRun(Runnable action);
  • 45. #J8Async @JosePaumard CompletionStage – chaînageCompletionStage – chaînage • Chaînage après, autre thread (common FJ pool) public <U> CompletionStage<U>  thenApplyAsync(Function<? super T,? extends U> fn); public CompletionStage<Void>  thenAcceptAsync(Consumer<? super T> action); public CompletionStage<Void>  thenRunAsync(Runnable action);
  • 46. #J8Async @JosePaumard CompletionStage – chaînageCompletionStage – chaînage • Chaînage après, autre thread (executor) public <U> CompletionStage<U>  thenApplyAsync(Function<? super T,? extends U> fn, Executor executor); public CompletionStage<Void>  thenAcceptAsync(Consumer<? super T> action, Executor executor); public CompletionStage<Void>  thenRunAsync(Runnable action, Executor executor);
  • 47. #J8Async @JosePaumard CompletionStage – compositionCompletionStage – composition • Composition public <U> CompletionStage<U>  thenCompose(Function<? super T, ? extends CompletionStage<U>> fn); public CompletionStage<Void>  thenComposeAsync( Function<? super T, ? extends CompletionStage<U>> fn); public CompletionStage<Void>  thenComposeAsync( Function<? super T, ? extends CompletionStage<U>> fn, Executor executor);
  • 48. #J8Async @JosePaumard Chaînage & compositionChaînage & composition • Ces deux familles de fonction permettent d’enchaîner une opération après l’autre
  • 49. #J8Async @JosePaumard Chaînage & compositionChaînage & composition • On peut aussi enchaîner une tâche à la suite de deux autres tâches public CompletionStage<V> thenCombine (CompletionStage<U> other,  BiFunction<T, U, V> function) ;
  • 50. #J8Async @JosePaumard Chaînage & compositionChaînage & composition • On peut aussi enchaîner une tâche à la suite de deux autres tâches • Prend les résultats de this et other  Et les combine dans function public CompletionStage<V> thenCombine (CompletionStage<U> other,  BiFunction<T, U, V> function) ;
  • 51. #J8Async @JosePaumard Chaînage & compositionChaînage & composition • On peut aussi enchaîner une tâche à la suite de deux autres tâches public CompletionStage<V> thenCombine (CompletionStage<U> other,  BiFunction<T, U, V> function) ; public CompletionStage<V> thenCombineAsync (CompletionStage<U> other,  BiFunction<T, U, V> function) ;
  • 52. #J8Async @JosePaumard Chaînage & compositionChaînage & composition • On peut aussi enchaîner une tâche à la suite de deux autres tâches public CompletionStage<V> thenCombine (CompletionStage<U> other,  BiFunction<T, U, V> function) ; public CompletionStage<V> thenCombineAsync (CompletionStage<U> other,  BiFunction<T, U, V> function, Executor executor) ;
  • 53. #J8Async @JosePaumard Chaînage & compositionChaînage & composition • Versions avec Consumer public CompletionStage<Void> thenAcceptBoth (CompletionStage<U> other,  BiConsumer<T, U> action) ; public CompletionStage<Void> thenAcceptBothAsync (CompletionStage<U> other,  BiConsumer<T, U> action) ; public CompletionStage<Void> thenAcceptBothAsync (CompletionStage<U> other,  BiConsumer<T, U> action, Executor executor) ;
  • 54. #J8Async @JosePaumard Chaînage & compositionChaînage & composition • Versions avec Runnable public CompletionStage<Void> runAfterBoth (CompletionStage<?> other,  Runnable action) ; public CompletionStage<Void> runAfterBothAsync (CompletionStage<?> other,  Runnable action) ; public CompletionStage<Void> runAfterBothAsync (CompletionStage<?> other,  Runnable action, Executor executor) ;
  • 55. #J8Async @JosePaumard Chaînage & compositionChaînage & composition • Ces tâches se déclenchent conditionnellement à this et à la tâche passée en paramètre • Lorsque ces tâches sont terminées • On peut aussi déclencher lorsque la première se termine
  • 56. #J8Async @JosePaumard Chaînage multipleChaînage multiple • Version function public CompletionStage<V> applyToEither (CompletionStage<? extends T> other,  Function<T, U> function) ;
  • 57. #J8Async @JosePaumard Chaînage multipleChaînage multiple • Version function public CompletionStage<U> applyToEither (CompletionStage<? extends T> other,  Function<T, U> function) ; public CompletionStage<U> applyToEitherAsync (CompletionStage<? extends T> other,  Function<T, U> function) ; public CompletionStage<U> applyToEitherAsync (CompletionStage<? extends T> other,  Function<T, U> function, Executor executor) ;
  • 58. #J8Async @JosePaumard Chaînage multipleChaînage multiple • Version consumer public CompletionStage<V> acceptEither (CompletionStage<? extends T> other,  Consumer<? extends T> consumer) ; public CompletionStage<V> acceptEitherAsync (CompletionStage<? extends T> other,  Consumer<? extends T> consumer) ; public CompletionStage<V> acceptEitherAsync (CompletionStage<? extends T> other,  Consumer<? extends T> consumer, Executor executor) ;
  • 59. #J8Async @JosePaumard Chaînage multipleChaînage multiple • Version runnable public CompletionStage<V> runAfterEither (CompletionStage<U> other,  Runnable action) ; public CompletionStage<V> runAfterEitherAsync (CompletionStage<U> other,  Runnable action) ; public CompletionStage<V> runAfterEitherAsync (CompletionStage<U> other,  Runnable action, Executor executor) ;
  • 60. #J8Async @JosePaumard Création sur plusieurs tâchesCréation sur plusieurs tâches • Méthodes statiques public static CompletableFuture<Void>  allOf(CompletableFuture<?>... cfs) ; public static CompletableFuture<Object>  anyOf(CompletableFuture<?>... cfs) ;
  • 61. #J8Async @JosePaumard Création sur plusieurs tâchesCréation sur plusieurs tâches • Attention à la sémantique ! • Imprime « null » public static CompletableFuture<Void>  allOf(CompletableFuture<?>... cfs) ; CompletableFuture<Void> allOf = CompletableFuture.allOf() ; System.out.println("allOF : " + allOf.join()) ;
  • 62. #J8Async @JosePaumard Création sur plusieurs tâchesCréation sur plusieurs tâches • Attention à la sémantique ! • Ne rend pas la main… public static CompletableFuture<Void>  allOf(CompletableFuture<?>... cfs) ; CompletableFuture<Object> anyOf = CompletableFuture.anyOf() ; System.out.println("anyOf : " + anyOf.join()) ;
  • 63. #J8Async @JosePaumard Création sur plusieurs tâchesCréation sur plusieurs tâches • Attention à la sémantique ! public static CompletableFuture<Void>  allOf(CompletableFuture<?>... cfs) ; CompletableFuture<Object> anyOf = CompletableFuture.anyOf() ; System.out.println("anyOf : " + anyOf.getNow("Nothing to say")) ;
  • 64. #J8Async @JosePaumard Gestion des exceptionsGestion des exceptions • Point délicat :  Une première étape consiste à créer les tâches et à décrire leur enchaînement  L’exécution des tâches démarre indépendamment des appels  À chaque étape, un CompletableFuture est créé
  • 65. #J8Async @JosePaumard Gestion des exceptionsGestion des exceptions • Un CompletableFuture peut dépendre :  Cas 1 : d’un autre CompletableFuture  Cas 2 : de deux autres CompletableFuture  Cas 3 : de N CompletableFuture
  • 66. #J8Async @JosePaumard Gestion des exceptionsGestion des exceptions • Une exception est jetée dans le cas 1  Tous les CompletableFuture sont en erreur • Ils se terminent « exceptionnellement »  isExceptionnaly() retourne true  L’appel à get() jette une ExecutionException  get().getCause() retourne l’exception première
  • 67. #J8Async @JosePaumard Gestion des exceptionsGestion des exceptions • Une exception est jetée dans le cas 2  Tous les CompletableFuture en aval sont en erreur • Ils se terminent « exceptionnellement » • L’autre tâche peut se terminer normalement  On peut l’interroger par get() pour avoir son résultat
  • 68. #J8Async @JosePaumard Gestion des exceptionsGestion des exceptions • Une exception est jetée dans le cas 3  Le CompletableFuture retourné est en erreur • Il se termine « exceptionnellement » • Les autres tâches peuvent se terminer normalement  On peut l’interroger par get() pour avoir son résultat
  • 69. #J8Async @JosePaumard Gestion des exceptionsGestion des exceptions • On peut aussi traiter une exception normalement  Dans ce cas, l’exception est passée à la fonction  Utile pour les checked exception CompletionStage<T> exceptionally( Function<Throwable, ? extends T> function);
  • 70. #J8Async @JosePaumard Gestion des exceptionsGestion des exceptions • Méthode whenComplete()  Dans ce cas t ou e est nul dans l’appel de action  Le CompletableFuture retourné peut ne pas être en erreur CompletionStage<T> whenComplete (BiConsumer<T, Throwable> action) ;
  • 71. #J8Async @JosePaumard Gestion des exceptionsGestion des exceptions • Méthode whenComplete() CompletionStage<T> whenComplete (BiConsumer<T, Throwable> action) ; CompletionStage<T> whenCompleteAsync (BiConsumer<T, Throwable> action) ; CompletionStage<T> whenCompleteAsync (BiConsumer<T, Throwable> action, Executor executor) ;
  • 72. #J8Async @JosePaumard Gestion des exceptionsGestion des exceptions • Méthode handle()  Dans ce cas t ou e est nul dans l’appel de function  Retourne un CompletableFuture qui peut ne pas être en erreur CompletionStage<T> handle (BiFunction<T, Throwable, U> function) ;
  • 73. #J8Async @JosePaumard Gestion des exceptionsGestion des exceptions • Méthode handle() CompletionStage<T> handle (BiFunction<T, Throwable, U> function) ; CompletionStage<T> handleAsync (BiFunction<T, Throwable, U> function) ; CompletionStage<T> handleAsync (BiFunction<T, Throwable, U> function, Executor executor) ;
  • 74. #J8Async @JosePaumard Une dernière méthodeUne dernière méthode • CompletableFuture : On peut obtenir une estimation du nombre de tâches qui attendent l’exécution d’une tâche donnée int getNumberOfDependents() ;
  • 75. #J8Async @JosePaumard Exemple – 1Exemple – 1 • Lecture asynchrone de liens et affichage CompletableFuture.supplyAsync( () ‐> readPage("http://whatever.com/") )
  • 76. #J8Async @JosePaumard Exemple – 1Exemple – 1 • Lecture asynchrone de liens et affichage CompletableFuture.supplyAsync( () ‐> readPage("http://whatever.com/") ) .thenApply(page ‐> linkParser.getLinks(page))
  • 77. #J8Async @JosePaumard Exemple – 1Exemple – 1 • Lecture asynchrone de liens et affichage CompletableFuture.supplyAsync( () ‐> readPage("http://whatever.com/") ) .thenApply(page ‐> linkParser.getLinks(page)) .thenAccept( links ‐> displayPanel.display(links) ) ;
  • 78. #J8Async @JosePaumard Exemple – 1Exemple – 1 • Lecture asynchrone de liens et affichage CompletableFuture.supplyAsync( () ‐> readPage("http://whatever.com/") ) .thenApply(page ‐> linkParser.getLinks(page)) .thenAcceptAsync( links ‐> displayPanel.display(links), executor ) ;
  • 79. #J8Async @JosePaumard Exemple – 1Exemple – 1 • Lecture asynchrone de liens et affichage public interface Executor { void execute(Runnable command); }
  • 80. #J8Async @JosePaumard Exemple – 1Exemple – 1 • Lecture asynchrone de liens et affichage public interface Executor { void execute(Runnable command); } Executor executor = runnable ‐> SwingUtilities.invokeLater(runnable) ;
  • 81. #J8Async @JosePaumard Exemple – 1Exemple – 1 • Lecture asynchrone de liens et affichage CompletableFuture.supplyAsync( () ‐> readPage("http://whatever.com/") ) .thenApply(page ‐> linkParser.getLinks(page)) .thenAcceptAsync( links ‐> displayPanel.display(links),  runnable ‐> SwingUtilities.invokeLater(runnable) ) ;
  • 82. #J8Async @JosePaumard Exemple – 1Exemple – 1 • Lecture asynchrone de liens et affichage CompletableFuture.supplyAsync( () ‐> readPage("http://whatever.com/") ) .thenApply(Parser::getLinks) .thenAcceptAsync( DisplayPanel::display,  SwingUtilities::invokeLater ) ;
  • 83. #J8Async @JosePaumard Exemple – 2Exemple – 2 • Événements asynchrones dans CDI @Inject Event<String> event ; event.fire("some event") ; // returns void public void observes(@Observes String payload) { // handle the event, called in the firing thread }
  • 84. #J8Async @JosePaumard Exemple – 2Exemple – 2 • Événements asynchrones dans CDI public void observes(@Observes String payload) { // handle the event, called in the firing thread CompletableFuture.anyOf(/* some task */) ; }
  • 85. #J8Async @JosePaumard Exemple – 2Exemple – 2 • Événements asynchrones dans CDI @Inject Event<String> event ; event.fireAsync("some event") ; // returns CompletableFuture<Object> (?) public void observes(@Observes String payload) { // handle the event in another thread }
  • 86. #J8Async @JosePaumard Exemple – 2Exemple – 2 • Événements asynchrones dans CDI @Inject Event<String> event ; event.fireAsync("some event", executor) ;  public void observes(@Observes String payload) { // handle the event in the executor }
  • 87. #J8Async @JosePaumard Exemple – 2Exemple – 2 • Événements asynchrones dans CDI @Inject Event<String> event ; event.fireAsync("some event", executor) ;  @Produces @SwingExecutor Executor executor = SwingUtilities::invokeLater public void observes(@Observes String payload,  @SwingExecutor Executor executor) { // handle the event in the Swing thread }
  • 88. #J8Async @JosePaumard Exemple – 2Exemple – 2 • Événements asynchrones dans CDI @Inject Event<String> event ; event.fireAsync("some event", executor) ;  @Produces @SwingExecutor Executor executor = SwingUtilities::invokeLater public void observes(@Observes @SwingExecutor String payload) { // handle the event in the Swing thread }
  • 89. #J8Async @JosePaumard Exemple – 3Exemple – 3 CompletableFuture<String> closing = new CompletableFuture<String>() ; Stream<String> manyStrings = Stream.of("one", "two", "three") ; CompletableFuture<String> reduce = manyStrings .onClose(() ‐> { closing.complete("Closed") ; }) .map(CompletableFuture::completedFuture) .reduce( closing,   (cf1, cf2) ‐> cf1.thenCombine(cf2, function) // concatenation ) ; manyStrings.close() ;
  • 90. #J8Async @JosePaumard L’indispensable !L’indispensable ! • Fixer la taille du Common Fork / Join Pool System.setProperty( "java.util.concurrent.ForkJoinPool.common.parallelism", 2) ;
  • 91. #J8Async @JosePaumard ConclusionConclusion • On a une API pour le calcul asynchrone dans le JDK !
  • 92. #J8Async @JosePaumard ConclusionConclusion • On a une API pour le calcul asynchrone dans le JDK ! • Très riche et souple à l’utilisation
  • 93. #J8Async @JosePaumard ConclusionConclusion • On a une API pour le calcul asynchrone dans le JDK ! • Très riche et souple à l’utilisation • Construite sur l’utilisation des lambda
  • 94. #J8Async @JosePaumard ConclusionConclusion • On a une API pour le calcul asynchrone dans le JDK ! • Très riche et souple à l’utilisation • Construite sur l’utilisation des lambda • Permet un contrôle fin des threads
  • 95. #J8Async @JosePaumard ConclusionConclusion • On a une API pour le calcul asynchrone dans le JDK ! • Très riche et souple à l’utilisation • Construite sur l’utilisation des lambda • Permet un contrôle fin des threads • Gère différents types de chaînage
  • 96. #J8Async @JosePaumard ConclusionConclusion • On a une API pour le calcul asynchrone dans le JDK ! • Très riche et souple à l’utilisation • Construite sur l’utilisation des lambda • Permet un contrôle fin des threads • Gère différents types de chaînage • Gère intelligemment les exceptions