Upload
hamed-oukhay
View
222
Download
0
Embed Size (px)
Citation preview
8/2/2019 Cours Asynchro
1/8
1
Cours 5: Taches versus Threads Asynchronisme et multi-threading
Franoise Baude
u - rea ng, mu - ac es easynchronisme
1. Thread Pool et Executor
2. Taches avec rsultat, et asynchrones
8/2/2019 Cours Asynchro
2/8
2
Thread Pool et Executor: motivation Une thread sert mener bien le droulement dune
tache
Modle simple (simpliste!): Cration dune thread pour chaque nouvelle tache
Ok pour raliser un prototype
Mais peu performant si beaucoup de threads car gestion dunethread consomme temps et mmoire:
Cration et destruction: surcout non ngligeable surtout si tachecourte !
Occupation mmoire pour reprsenter une thread dans JVM
Plutt se baser sur la notion de pool (rservoir) dethreads et affecter dynamiquement chaque tache une thread libre (par le biais dun executor )
Thread Pool: principes
Pre-instancier un rservoir de threads Dlai dexcution dune tache rduit
Pas besoin de crer la thread a chaque nouvelle tache
=>Surcout de cration des threads amorti sur lensembledes taches qui seront excutes
Limite lexplosion mmoire JVM Nombre de threads peut par ex. tre fonction du nombre
de cores
Gestion liste des taches soumission +affectation sur threads Pas forcement trivial ! Voir exemple ci aprs
Plusieurs ThreadPool et Executors disponibles dansjava.util.concurrent
8/2/2019 Cours Asynchro
3/8
3
Thread Pool: exemple dimplantation
[B. Goetz]
Permet de soumettre unePermet de soumettre unetachetache auprauprs des de llexexcuteurcuteur
de tachesde taches
Thread Pool: difficults
Une tache runnable peut se bloquer, donc lathread qui excute la tache aussi
Rajoute un risque dinterblocage Plus de threads disponible permettant de faire progresser une
tache, qui une fois termine pourrait en dbloquer une Trop de taches bloques => plus, ou presque plus de
threads disponibles ( thread leakage )
Compromis habituel entre gain et overheads! Beaucoup de taches : stockage important pour taches en
attente (versus une thread / tache)
Trouver la bonne taille pour le pool de threads: fonctionsdu nombre de cores, types de taches (I/O-bound ou CPU-bound)
8/2/2019 Cours Asynchro
4/8
4
Executor : mode dutilisation Si r est un objet Runnable , et e un objet Executor
Remplacer: (new Thread(r)).start(); par e.execute(r);
Une implmentation d Executor est libre de choisircomment grer laffectation des taches aux threads The Executor interface does not strictly require that execution be
asynchronous. In the simplest case, an executor can run the submittedtask immediately in the caller's thread:
More typically, tasks are executed in some thread other than the
caller's thread. The executor below spawns a new thread for eachtask:
Ex:java.util.concurrent.ThreadPoolExecutor: implmentation dunExecutor utilisant 1 pool de threads
classclassDirectExecutorDirectExecutorimplementsimplementsExecutorExecutor{{
publicpublicvoidvoidexecuteexecute((RunnableRunnabler) { r.run(); } }r) { r.run(); } }
classclassThreadPerTaskExecutorThreadPerTaskExecutorimplementsimplementsExecutorExecutor{{
publicpublicvoidvoidexecuteexecute((RunnableRunnabler) { new Thread(r).r) { new Thread(r).startstart(); } }(); } }
Une grande varit d Executor sophistiqus
java.util.concurrent.Executors.newCachedThreadPool
public static ExecutorServicenewCachedThreadPool(ThreadFactory threadFactory) Creates a thread pool that creates new threads as needed,
but will reuse previously constructed threads when they areavailable, and uses the provided ThreadFactory to create newthreads when needed.
public interface ExecutorService extends Executor An Executor that provides methods to manage termination
and methods that can produce a Future for tracking progressof one or more asynchronous tasks. An ExecutorService can be shut down, which will cause it to
reject new tasks. Two different methods are provided forshutting down an ExecutorService. The shutdown() method willallow previously submitted tasks to execute before terminating,while the shutdownNow() method prevents waiting tasks fromstarting and attempts to stop currently executing tasks
8/2/2019 Cours Asynchro
5/8
5
Multi-threading, multi-taches et
asynchronisme1. Thread Pool et Executor
2. Taches avec rsultat, et asynchrones
Callable : motivation
Lorsque une tache (qui sera excute par unethread) doit renvoyer un rsultat :
Au lieu detre Runnable
Elle est Callable
java.util.concurrent Interface Callable
Type Parameters:
V - the result type of method call
8/2/2019 Cours Asynchro
6/8
6
Oscar Nierstrasz
Liveness and Asynchrony
11
Futures
Futures allow a client to continue in parallel witha host until the future value is needed:
Tache avec rsultat excute enasynchrone : Future et ExecutorService
Problme du lutilisation dun Executor: soumission dune tache un executor Souhait: Excution de la tache par une thread en mode asynchrone On ne sait donc pas quand le rsultat de la tache va tre disponible
Solution: le rsultat de la tache est manipul par le biais dun Future,
renvoy immdiatement lors de la soumission, reprsente une promesse de rponse Permet de senqurir de lavancement de la tache, voire lannuler
ExecutorServices provide methods arranging asynchronousexecution of any function expressed as Callable, the result-bearing analog of Runnable Future submit(Callable task) T invokeAny(Collection
8/2/2019 Cours Asynchro
7/8
7
Future interface java.util.concurrent Interface Future
Type Parameters: V - The result type returned by this Future's get method
The result can only be retrieved using method getwhen the computation has completed, blocking ifnecessary until it is ready to immediately block waiting for a task:result = exec.submit(aCallable).get();
boolean isDone()
Returns true if the corresponding task completed. result = exec.submit(aCallable);while (! result.isDone()){ do something else in parallel}result.get();
Cancellation is performed by the cancel method
Exemple [R. Lorimerhttp://www.javalobby.org/forums/thread.jspa?messageID=91836328]
8/2/2019 Cours Asynchro
8/8
8
Gestion de Futures transparents Principe:
appel de mthode sur un objet, qui doit renvoyer un retour: La rponse est un futur, mais transparent pour lappelant
Wait by Necessity: blocage automatique tant que la rponsenest pas disponible
Extension avec des groupes dobjets de mme type Appel sur le groupe dobjets comme si ctait un seul Rcupre un groupe de futures
Comment ? Par une rification des appels de mthodes en Java Rajout de traitements Meta (Meta Object Protocol), dont RMI
Exemple: Logiciel OW2 ProActive Parallel Suite, quipe OASIS (Objets Actifs, Smantique, Internet, Scurit),
CNRS I3S-INRIA ActiveEon, StartUp Sophia-Antipolis