You are on page 1of 8

Cours 5: Taches versus Threads Asynchronisme et multi-threading

Franoise Baude

Multi-threading, multi-taches et asynchronisme


1. 2. Thread Pool et Executor Taches avec rsultat, et asynchrones

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 dune thread consomme temps et mmoire:
Cration et destruction: surcout non ngligeable surtout si tache courte ! Occupation mmoire pour reprsenter une thread dans JVM

Plutt se baser sur la notion de pool (rservoir) de threads 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 lensemble des 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 dans java.util.concurrent

Thread Pool: exemple dimplantation [B. Goetz]

Permet de soumettre une tache auprs de lexcuteur aupr ex de taches

Thread Pool: difficults


Une tache runnable peut se bloquer, donc la thread 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: fonctions du nombre de cores, types de taches (I/O-bound ou CPUbound)

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 choisir comment 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 submitted task immediately in the caller's thread:
class DirectExecutor implements Executor { public void execute(Runnable r) { r.run(); } } execute( More typically, tasks are executed in some thread other than the caller's thread. The executor below spawns a new thread for each task: class ThreadPerTaskExecutor implements Executor { public void execute(Runnable r) { new Thread(r).start(); } } execute( Thread(r).start();

Ex: java.util.concurrent.ThreadPoolExecutor: implmentation dun Executor utilisant 1 pool de threads

Une grande varit d Executor sophistiqus


java.util.concurrent.Executors.newCachedThreadPool

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory)


Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available, and uses the provided ThreadFactory to create new threads when needed.

public interface ExecutorService extends Executor


An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks

Multi-threading, multi-taches et asynchronisme


1. 2. Thread Pool et Executor Taches avec rsultat, et asynchrones

Callable : motivation
Lorsque une tache (qui sera excute par une thread) doit renvoyer un rsultat :
Au lieu detre Runnable Elle est Callable java.util.concurrent Interface Callable<V> Type Parameters:
V - the result type of method call

Liveness and Asynchrony

Futures
Futures allow a client to continue in parallel with a host until the future value is needed:

Oscar Nierstrasz

11

Tache avec rsultat excute en asynchrone : 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 asynchronous execution of any function expressed as Callable, the resultbearing analog of Runnable
<T> Future<T> submit(Callable<T> task) <T> T invokeAny(Collection<? extends Callable<T>> tasks) <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)

ThreadPoolExecutor implmente ExecutorService (et Executor)

Future interface
Interface Future<V> Type Parameters:
java.util.concurrent V - The result type returned by this Future's get method

The result can only be retrieved using method get when the computation has completed, blocking if necessary 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. Lorimer


http://www.javalobby.org/forums/thread.jspa?messageID=91836328

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 rponse nest 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

You might also like