SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation
ForkJoin

Multithreading en Java

Eléments conceptuels de programmation concurrente
Elvadas NONO
Softeam Cadextan , Startech Java

October 16, 2013

1 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation

Outline
1
2
3
4

5

6

ForkJoin

Threads: the Origin
Callable
Future
ThreadPool
Executor
ExecutorService
Executors
Synchronisation 1
Synchronized
ReentrantLock
ReadWriteLock
Synchronisation
CountDownLatch
CyclicBarrier
2 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation

Thread

ForkJoin

Thread: Plus petite unité d'exécution dans un programme.
Application: Ensemble de Threads s'exécutant en parallèle
dans la JVM
Non Deamon Thread vs Deamon Thread, Main Thread
Notion de priorité d'un Thread
Deux façons de créer un Thread:
extends java.lang.Thread Class
Implement java.lang.Runnable Interface

3 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation
ForkJoin

/∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗ OPTION1∗∗∗∗∗∗∗∗∗∗∗∗∗/
public

class MonThread extends Thread {
public void run() {
// Thread behavior goes here !!

.

.

.

}
}
// Start Thread
MonTread t1= new MonThread();
t1 . start () ;

/∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗ OPTION2∗∗∗∗∗∗∗∗∗∗∗∗∗/
public

class MyRunnable implements Runnable {
public void run() {
// Thread behavior goes here !!

.

.

.

}
}

Thread t2= new Thread ( new MyRunnable());
t2 . start () ;

4 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation
ForkJoin

Problèmes
Et le résultat ? retour de la methode run: void
gestion des exceptions
démarrage du thread
synchrone ou asynchrone?

4 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation

L'interface Callable

ForkJoin

public Interface Callable<V>
java.util.concurrent package, since JDK 1.5
Dénit une unique methode sans argument call.
Retourne un résultat Générique V
Peut lever une exception

5 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation
ForkJoin

public class MyCallable implements CallableString {

}

public String call() throws exception {
// Thread behavior goes here!!
}

. . .

6 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation
ForkJoin
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Executor
ExecutorService
Executors

Synchronisation
ForkJoin

Executor

L'interface Executor: Découpler la soumission des tâches
concurrentes des mécanismes d'exécution de chaque tâche
Méthodes fournies
void execute(Runnable command) Exécuter la commande
passée en paramètre dans le future
Futurev submit = executor.submit(worker);
ListFutureT invokeAll(Collection? extends
CallableT tasks) Lien Future/Callable/Executor

Variantes
ExecutorService
ThreadPoolExeceutor
Serial, Parallel, Cache, etcc
7 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Executor
ExecutorService
Executors

Synchronisation

ExecutorService

ForkJoin

ExecutorService: Spécialisation de l'interface Executor an de
soumettre des
Runnable
Callable
Collection de Callable
Collection de Runnable
Sous ensemble de Runnable/Callable

8 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Executor
ExecutorService
Executors

Synchronisation
ForkJoin

Executors

Factory de ThreadPool / Executor
Créé un
exécuteur ociant avec un seul worker thread et une queue de
traitement.
static ExecutorService newSingleThreadExecutor()

static ExecutorService newFixedThreadPool(int nThreads)

pool de

Threads faisant usage d'une le de tâches.
Pool
fonctionnant suivant le sytème de cache
nThread

static ExecutorService newCachedThreadPool()
static ScheduledExecutorService

Executeur pouvant
lancer des threads périodiques, avec des délais
newSingleThreadScheduledExecutor()

9 / 20
Threads

for

the Origin
Callable
Future

ThreadPool
Synchronisation 1

Executor
ExecutorService
Executors

Synchronisation
ForkJoin

public class PoolThreadTest {
private static final int NB_TASKS = 100;
public static void main(String args[]){
// Execultor service Factory
ExecutorService cacheExecutor =
Executors.newCachedThreadPool();
ExecutorService singleExecutor =
Executors.newSingleThreadExecutor();
ExecutorService fixedExecutor =
Executors.newFixedThreadPool(3);
// Create a task list
CollectionDummyCallable tasks= new
9 / 20
Threads

executor

the Origin
Callable
Future
ThreadPool

Synchronisation 1

Executor
ExecutorService
Executors

Synchronisation
ForkJoin

ArrayList(NB_TASKS);
for(int i=0;iNB_TASKS;i++){
t= new DummyCallable(i);
tasks.add(t);
}

DummyCallable

//start executor
startExecutor(fixedExecutor, tasks);
}
private static void startExecutor(ExecutorService
fixedExecutor, CollectionDummyCallable tasks) {
try {

ListFutureLong
9 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Executor
ExecutorService
Executors

Synchronisation
ForkJoin

futures=executor.invokeAll(tasks);
executor.awaitTermination(1, TimeUnit.MINUTES);
catch (InterruptedException |
IllegalStateException e) {
e.printStackTrace();
}finally{
executor.shutdown();
System.out.println(bye bye!);
}
}

}

10 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Executor
ExecutorService
Executors

Synchronisation
ForkJoin

ScheduledExecutorService
Exécuter des tâches
Après un délai

schedule (Callable task, long delay, TimeUnit timeunit)
schedule (Runnable task, long delay, TimeUnit timeunit)

A une fréquence xe: example toutes les 5min
scheduleAtFixedRate (Runnable, long initialDelay, long period,
TimeUnit timeunit)

Avec un délai xe entre la n d'un Run et le début du suivant
scheduleWithFixedDelay (Runnable, long initialDelay, long
period, TimeUnit timeunit)

Comme tous les Executeurs vous devez les arrêter
explicitement après usage
10 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Synchronized
ReentrantLock
ReadWriteLock

Synchronisation
ForkJoin

ScheduledExecutorService ses =
Executors.newScheduledThreadPool(5);
ScheduledFuture sf = ses.schedule(new Callable() {
public Object call() throws Exception {
System.out.println(Executed!);
return StarTech Java!;
}
},
5,
TimeUnit.SECONDS);
System.out.println(result =  + sf.get());
ses.shutdown();

11 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Synchronized
ReentrantLock
ReadWriteLock

Synchronisation

Synchronized

ForkJoin

Protection de l'accès aux sections critiques
Implémentation d'un lock structuré:synchronized methods and
synchronized statements
Interdit l'exécution concurrente de regions protégées sur un
même objet par deux Threads
Reentrant mechanism

11 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Synchronized
ReentrantLock
ReadWriteLock

Synchronisation
ForkJoin

//***********SOLUTION1
public static synchronized Singleton getInstance(){
if (instance==null)
//1
instance=new Singleton();
//2
return instance;
//3
}
//*************SOLUTION2
public static Singleton getInstance(){
if (instance==null) {
//1
synchronized (Singleton.class){ //2
instance=new Singleton();
}
}
return instance;
}
11 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Synchronized
ReentrantLock
ReadWriteLock

Synchronisation
ForkJoin

// Q:which one is correct? A: None Why?

12 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Synchronized
ReentrantLock
ReadWriteLock

Synchronisation

Synchronized issues

ForkJoin

Problèmes
Thread automatiquemnt bloqué si le verrou est occupé
Pas de vue sur la le des Threads bloqués et reprise après lock
Gestion des locks multiples
Lock Structuré
Unfair Lock
No way to check ability to trying for lock interruptibly
No delay/timeout waiting period
Dierence Read/Write operations
12 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Synchronized
ReentrantLock
ReadWriteLock

Synchronisation

ReetrantLock

ForkJoin

ReetrantLock: Lock Reentrant plus exible
Fairness: The most waiting Thread is always choosen if
activated
Specialisation: ReaderLock and WritterLock
Waiting Thread Queue
tryLock to check if lock is available : not blockant

13 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

Synchronized
ReentrantLock
ReadWriteLock

Synchronisation

ReadWriteLock

ForkJoin

ReadWriteLock: Interface de gestion d'un lock en
Lecture/Ecriture
Plusieurs Lecteurs autorisés en parallèle
Les Rédacteurs sont prioritaires sur les lecteurs
En interne: Deux lock séparés
ReentrantReadWriteLock implements ReadWriteLock

14 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

CountDownLatch
CyclicBarrier
Phaser

Synchronisation
ForkJoin

ReadWriteLock readWriteLock = new
ReentrantReadWriteLock();
readWriteLock.readLock().lock();
// Plusieurs Lecteur peuvent entrer dans cette section
// si le verrou n'est pas occupé par un Redacteur, et
aucun rédacteur en Attente du verrou
readWriteLock.readLock().unlock();
readWriteLock.writeLock().lock();
// seuls les Redacteurs peuvent atteindre cette
section,
// si aucun lecteur actif.
readWriteLock.writeLock().unlock();

15 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

CountDownLatch
CyclicBarrier
Phaser

Synchronisation

CountDownLatch

ForkJoin

Permettre à un ou plusieurs Thread d'attendre la n de
l'exécution d'un ensemble d'actions par un ou plusieurs autres
Threads
un CountDownLatch est initialisé avec un compteur
la méthode countDown() décrémente le compteur
la méthode await() bloque le Thread appelant jusqu'a ce que
le compteur atteigne la valeur zero
Tous les Thread bloqués sont libérés lorsque le compteur
devient nul
le compteur ne peut pas être réinitialisé.
Tout appel à await après que le compteur soit passé à zero se
termine imédiatement

15 / 20
Threads the Origin
Callable
Future
ThreadPool
Synchronisation 1

CountDownLatch
CyclicBarrier
Phaser

Synchronisation
ForkJoin

final CountDownLatch countDownLatch = new
CountDownLatch(2);
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println(countDownLatch.getCount());
//(2)
countDownLatch.countDown();
System.out.println(countDownLatch.getCount());
//(1)
try {
Thread.sleep(5000);
countDownLatch.countDown();
System.out.println(countDownLatch.getCount());
//(0)
} catch (InterruptedException e) {
e.printStackTrace();
15 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

CountDownLatch
CyclicBarrier
Phaser

Synchronisation
ForkJoin

}
});

}

t.start();
try {
countDownLatch.await(); //blocks the current Thread
System.out.println(MainThread
+countDownLatch.getCount()); // run only when latch=0
} catch (InterruptedException e) {
e.printStackTrace();
}

16 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

CountDownLatch
CyclicBarrier
Phaser

Synchronisation

CyclicBarrier

ForkJoin

Permettre à un ou plusieurs Thread de s'attendre à un point
de rendez vous.
un CyclicBarrier est initialisé avec un compteur
Contrairement au CountDownLatch, le compteur peut être
réinitialisé pour un nouveau cycle: reset
la méthode await() bloque le Thread appelant jusqu'a ce que
l'une des conditions suivantes soit vériée
le compteur atteind la valeur

zero naturellement ou par un

appel à reset

Le Thread appelant est interrompu par un autre Thread
un Thread en attente du RDV atteind son timeout

Tous les Thread bloqués sont libérés lorsque le compteur
devient nul ou le compteur ressetté

16 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

CountDownLatch
CyclicBarrier
Phaser

Synchronisation
ForkJoin

//create a Cyclic Barrier
CyclicBarrier barrier = new CyclicBarrier(5);
//Make the current thread wait at barrier
barrier.await();
//after 15s the Thread is release even if the counter is
not 0
barrier.await(15, TimeUnit.SECONDS);
//define a barrier action
Runnable
barrierAction = new Runnable( ... ;
CyclicBarrier barrier
= new CyclicBarrier(3,
barrierAction);

17 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1

CountDownLatch
CyclicBarrier
Phaser

Synchronisation

Phaser

ForkJoin

Mécanisme de synchornisation à un point de rendez vous
similaire au CyclicBarrier
Supporte plusieurs cycles, JDK 7
le nombre de parties n'est pas xé à l'avance: dynamique au l
du temps et des cycles
l'enregistrement se fait à tout moment: methode register
Atteindre le point de RDV int arrive() / et se désister du
prochain cycle arriveAndDeregister()
boolean onAdvance(int phase, int registeredParties), réagir aux
changement de cycles
int arriveAndAwaitAdvance() attendre les autres Threads au
point de rendez vous.

17 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation
ForkJoin

Fork/Join

Programmation Multi-Core, DPR algorithm,JSR 166 libs,
native in JDK7
ForkJoinPool

Fixed Pool Size Thread, if no size specied= Number of
available processors
ExecutorService permettant d'exécuter des ForkJoinTasks
Un Thread peut récupérer une tâche dans la le d'attente d'un
autre Thread
fork:

subdiviser un traitement en plusieurs sous traitements
parallèles
RecursiveTask  RecursiveAction: sous classes de
ForkJoinTask
join:

Récupérer le résultat d'une sous tâche

18 / 20
Threads

public

the Origin
Callable
Future
ThreadPool

Synchronisation 1
Synchronisation
ForkJoin

18 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation
ForkJoin

public class MaxSearchTask extends RecursiveTask{
protected Long compute() {
if(sup-inf5){
return simpleMax(); }
else{
int mid=(inf+sup)/2;
MaxSearchTask search1 = new MaxSearchTask(inf,mid, t);
MaxSearchTask search2 = new MaxSearchTask(mid, sup, t);
invokeAll(search1,search2);
return Math.max((Long)search1.join(),(Long)
search2.join());
}
...
}

19 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation

Multithreading is also

ForkJoin

Types Atomiques, AtomicInteger, AtomicXXX
Volatile: The volatile force the thread to update the original
variable.
Utiliser les collections appropriées en fonction des situations:
Thread safe collections vs non Thread safe collections
BlockingQueue

Outils de proling: JProler, VisualVM,
Debugging, JDWP
...
19 / 20
Threads: the Origin
Callable
Future
ThreadPool
Synchronisation 1
Synchronisation

QA

ForkJoin

Now this is not the end.
It is not even the beginning of the end.
But it is, perhaps, the end of the beginning.
Winston Churchill

20 / 20

Mais conteúdo relacionado

Mais procurados

Ces outils qui vous font gagner du temps
Ces outils qui vous font gagner du tempsCes outils qui vous font gagner du temps
Ces outils qui vous font gagner du tempsAntoine Rey
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database ConnectivityKorteby Farouk
 
Run java vs ruby
Run java vs rubyRun java vs ruby
Run java vs rubypinguin666
 
Workshop Spring - Session 4 - Spring Batch
Workshop Spring -  Session 4 - Spring BatchWorkshop Spring -  Session 4 - Spring Batch
Workshop Spring - Session 4 - Spring BatchAntoine Rey
 
"Input/Ouput, 16 ans après" à Devoxx France 2012
"Input/Ouput, 16 ans après" à Devoxx France 2012"Input/Ouput, 16 ans après" à Devoxx France 2012
"Input/Ouput, 16 ans après" à Devoxx France 2012Jean-Michel Doudoux
 
Retours Devoxx France 2016
Retours Devoxx France 2016Retours Devoxx France 2016
Retours Devoxx France 2016Antoine Rey
 

Mais procurados (8)

Ces outils qui vous font gagner du temps
Ces outils qui vous font gagner du tempsCes outils qui vous font gagner du temps
Ces outils qui vous font gagner du temps
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Run java vs ruby
Run java vs rubyRun java vs ruby
Run java vs ruby
 
Reseau
ReseauReseau
Reseau
 
Java Nio 2
Java Nio 2Java Nio 2
Java Nio 2
 
Workshop Spring - Session 4 - Spring Batch
Workshop Spring -  Session 4 - Spring BatchWorkshop Spring -  Session 4 - Spring Batch
Workshop Spring - Session 4 - Spring Batch
 
"Input/Ouput, 16 ans après" à Devoxx France 2012
"Input/Ouput, 16 ans après" à Devoxx France 2012"Input/Ouput, 16 ans après" à Devoxx France 2012
"Input/Ouput, 16 ans après" à Devoxx France 2012
 
Retours Devoxx France 2016
Retours Devoxx France 2016Retours Devoxx France 2016
Retours Devoxx France 2016
 

Destaque

Cp con jefes epicos
Cp con jefes epicosCp con jefes epicos
Cp con jefes epicosRaulo Veira
 
Centro Formazione Aziende
Centro Formazione AziendeCentro Formazione Aziende
Centro Formazione AziendeErmanno Simeone
 
Dreamwares: Lightning Experience
Dreamwares: Lightning ExperienceDreamwares: Lightning Experience
Dreamwares: Lightning ExperienceAmit Ahuja
 
Advantages of Customer Relationship Management
Advantages of Customer Relationship ManagementAdvantages of Customer Relationship Management
Advantages of Customer Relationship ManagementSadia Yasmeen
 
JSS Winter Issue, Vol. 9, No. 4, Table of Contents
JSS Winter Issue, Vol. 9, No. 4, Table of ContentsJSS Winter Issue, Vol. 9, No. 4, Table of Contents
JSS Winter Issue, Vol. 9, No. 4, Table of ContentsJeremy Tamsett
 
AMERICA’S RENTAL HOUSING EVOLVING MARKETS AND NEEDS Joint Center for Housing ...
AMERICA’S RENTAL HOUSING EVOLVING MARKETS AND NEEDS Joint Center for Housing ...AMERICA’S RENTAL HOUSING EVOLVING MARKETS AND NEEDS Joint Center for Housing ...
AMERICA’S RENTAL HOUSING EVOLVING MARKETS AND NEEDS Joint Center for Housing ...JerryLewless
 
Diverted Homeowners, the Rental Crisis and Foregone Household Formation
Diverted Homeowners,  the Rental Crisis and Foregone Household FormationDiverted Homeowners,  the Rental Crisis and Foregone Household Formation
Diverted Homeowners, the Rental Crisis and Foregone Household FormationJerryLewless
 
DO SOMETHING NEW
DO SOMETHING NEWDO SOMETHING NEW
DO SOMETHING NEWDoug Oakes
 
131014 professione welfare brochure-v5_de_fhyperlink_def
131014 professione welfare brochure-v5_de_fhyperlink_def131014 professione welfare brochure-v5_de_fhyperlink_def
131014 professione welfare brochure-v5_de_fhyperlink_defAlessia Coeli
 
11 dossier nuova-ecologia-intervista m.molteni
11 dossier nuova-ecologia-intervista m.molteni11 dossier nuova-ecologia-intervista m.molteni
11 dossier nuova-ecologia-intervista m.molteniAlessia Coeli
 

Destaque (10)

Cp con jefes epicos
Cp con jefes epicosCp con jefes epicos
Cp con jefes epicos
 
Centro Formazione Aziende
Centro Formazione AziendeCentro Formazione Aziende
Centro Formazione Aziende
 
Dreamwares: Lightning Experience
Dreamwares: Lightning ExperienceDreamwares: Lightning Experience
Dreamwares: Lightning Experience
 
Advantages of Customer Relationship Management
Advantages of Customer Relationship ManagementAdvantages of Customer Relationship Management
Advantages of Customer Relationship Management
 
JSS Winter Issue, Vol. 9, No. 4, Table of Contents
JSS Winter Issue, Vol. 9, No. 4, Table of ContentsJSS Winter Issue, Vol. 9, No. 4, Table of Contents
JSS Winter Issue, Vol. 9, No. 4, Table of Contents
 
AMERICA’S RENTAL HOUSING EVOLVING MARKETS AND NEEDS Joint Center for Housing ...
AMERICA’S RENTAL HOUSING EVOLVING MARKETS AND NEEDS Joint Center for Housing ...AMERICA’S RENTAL HOUSING EVOLVING MARKETS AND NEEDS Joint Center for Housing ...
AMERICA’S RENTAL HOUSING EVOLVING MARKETS AND NEEDS Joint Center for Housing ...
 
Diverted Homeowners, the Rental Crisis and Foregone Household Formation
Diverted Homeowners,  the Rental Crisis and Foregone Household FormationDiverted Homeowners,  the Rental Crisis and Foregone Household Formation
Diverted Homeowners, the Rental Crisis and Foregone Household Formation
 
DO SOMETHING NEW
DO SOMETHING NEWDO SOMETHING NEW
DO SOMETHING NEW
 
131014 professione welfare brochure-v5_de_fhyperlink_def
131014 professione welfare brochure-v5_de_fhyperlink_def131014 professione welfare brochure-v5_de_fhyperlink_def
131014 professione welfare brochure-v5_de_fhyperlink_def
 
11 dossier nuova-ecologia-intervista m.molteni
11 dossier nuova-ecologia-intervista m.molteni11 dossier nuova-ecologia-intervista m.molteni
11 dossier nuova-ecologia-intervista m.molteni
 

Semelhante a Multi threadingJava

Programmation concurrente en Java
Programmation concurrente en JavaProgrammation concurrente en Java
Programmation concurrente en JavaFlorian Beaufumé
 
Wilfreid K. AGBO et Grégoire J. MONEYENGONO - Java thread
Wilfreid K. AGBO et Grégoire J. MONEYENGONO - Java threadWilfreid K. AGBO et Grégoire J. MONEYENGONO - Java thread
Wilfreid K. AGBO et Grégoire J. MONEYENGONO - Java threadWilfreid AGBO
 
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 2012slandelle
 
2014.12.11 - TECH CONF #3 - Présentation Node.js
2014.12.11 - TECH CONF #3 - Présentation Node.js2014.12.11 - TECH CONF #3 - Présentation Node.js
2014.12.11 - TECH CONF #3 - Présentation Node.jsTelecomValley
 
Autour de Node.js - TechConf#3
Autour de Node.js - TechConf#3Autour de Node.js - TechConf#3
Autour de Node.js - TechConf#3Luc Juggery
 
4 asynch task_services_thread
4 asynch task_services_thread4 asynch task_services_thread
4 asynch task_services_threadSaber LAJILI
 
Play Framework
Play FrameworkPlay Framework
Play FrameworkArmaklan
 
nouveautés du moteur Bonita 7.9
nouveautés du moteur Bonita 7.9nouveautés du moteur Bonita 7.9
nouveautés du moteur Bonita 7.9Bonitasoft
 
EventMachine
EventMachineEventMachine
EventMachineLeTesteur
 
Programmation web asynchrone avec Tornado
Programmation web asynchrone avec TornadoProgrammation web asynchrone avec Tornado
Programmation web asynchrone avec TornadoRonan Amicel
 
log file sous Netbeans et J2ME
log file sous Netbeans et J2MElog file sous Netbeans et J2ME
log file sous Netbeans et J2MEZied
 
Introduction to prograaming using ajax PHP JS
Introduction to prograaming using ajax PHP JSIntroduction to prograaming using ajax PHP JS
Introduction to prograaming using ajax PHP JSAliHusseini14
 
Workshop Spring 3 - Tests et techniques avancées du conteneur Spring
Workshop Spring  3 - Tests et techniques avancées du conteneur SpringWorkshop Spring  3 - Tests et techniques avancées du conteneur Spring
Workshop Spring 3 - Tests et techniques avancées du conteneur SpringAntoine Rey
 
Zend Framework 2
Zend Framework 2Zend Framework 2
Zend Framework 2epixelic
 
Plongée au cœur du Framework .NET 4.5
Plongée au cœur du Framework .NET 4.5Plongée au cœur du Framework .NET 4.5
Plongée au cœur du Framework .NET 4.5Microsoft
 
I le langage java d'una manière avancée introduction
I  le langage java d'una manière avancée introductionI  le langage java d'una manière avancée introduction
I le langage java d'una manière avancée introductionsabrine_hamdi
 

Semelhante a Multi threadingJava (20)

Programmation concurrente en Java
Programmation concurrente en JavaProgrammation concurrente en Java
Programmation concurrente en Java
 
Wilfreid K. AGBO et Grégoire J. MONEYENGONO - Java thread
Wilfreid K. AGBO et Grégoire J. MONEYENGONO - Java threadWilfreid K. AGBO et Grégoire J. MONEYENGONO - Java thread
Wilfreid K. AGBO et Grégoire J. MONEYENGONO - Java thread
 
Support NodeJS avec TypeScript Express MongoDB
Support NodeJS avec TypeScript Express MongoDBSupport NodeJS avec TypeScript Express MongoDB
Support NodeJS avec TypeScript Express MongoDB
 
Nouveautés Java 9-10-11
Nouveautés Java 9-10-11Nouveautés Java 9-10-11
Nouveautés Java 9-10-11
 
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
 
2014.12.11 - TECH CONF #3 - Présentation Node.js
2014.12.11 - TECH CONF #3 - Présentation Node.js2014.12.11 - TECH CONF #3 - Présentation Node.js
2014.12.11 - TECH CONF #3 - Présentation Node.js
 
Autour de Node.js - TechConf#3
Autour de Node.js - TechConf#3Autour de Node.js - TechConf#3
Autour de Node.js - TechConf#3
 
4 asynch task_services_thread
4 asynch task_services_thread4 asynch task_services_thread
4 asynch task_services_thread
 
Play Framework
Play FrameworkPlay Framework
Play Framework
 
nouveautés du moteur Bonita 7.9
nouveautés du moteur Bonita 7.9nouveautés du moteur Bonita 7.9
nouveautés du moteur Bonita 7.9
 
EventMachine
EventMachineEventMachine
EventMachine
 
Programmation web asynchrone avec Tornado
Programmation web asynchrone avec TornadoProgrammation web asynchrone avec Tornado
Programmation web asynchrone avec Tornado
 
log file sous Netbeans et J2ME
log file sous Netbeans et J2MElog file sous Netbeans et J2ME
log file sous Netbeans et J2ME
 
Introduction to prograaming using ajax PHP JS
Introduction to prograaming using ajax PHP JSIntroduction to prograaming using ajax PHP JS
Introduction to prograaming using ajax PHP JS
 
Workshop Spring 3 - Tests et techniques avancées du conteneur Spring
Workshop Spring  3 - Tests et techniques avancées du conteneur SpringWorkshop Spring  3 - Tests et techniques avancées du conteneur Spring
Workshop Spring 3 - Tests et techniques avancées du conteneur Spring
 
Zend Framework 2
Zend Framework 2Zend Framework 2
Zend Framework 2
 
chapitre 2 Android 2.pptx
chapitre 2 Android 2.pptxchapitre 2 Android 2.pptx
chapitre 2 Android 2.pptx
 
Plongée au cœur du Framework .NET 4.5
Plongée au cœur du Framework .NET 4.5Plongée au cœur du Framework .NET 4.5
Plongée au cœur du Framework .NET 4.5
 
SdE 9 - Threads
SdE 9 - ThreadsSdE 9 - Threads
SdE 9 - Threads
 
I le langage java d'una manière avancée introduction
I  le langage java d'una manière avancée introductionI  le langage java d'una manière avancée introduction
I le langage java d'una manière avancée introduction
 

Multi threadingJava

  • 1. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronisation ForkJoin Multithreading en Java Eléments conceptuels de programmation concurrente Elvadas NONO Softeam Cadextan , Startech Java October 16, 2013 1 / 20
  • 2. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronisation Outline 1 2 3 4 5 6 ForkJoin Threads: the Origin Callable Future ThreadPool Executor ExecutorService Executors Synchronisation 1 Synchronized ReentrantLock ReadWriteLock Synchronisation CountDownLatch CyclicBarrier 2 / 20
  • 3. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronisation Thread ForkJoin Thread: Plus petite unité d'exécution dans un programme. Application: Ensemble de Threads s'exécutant en parallèle dans la JVM Non Deamon Thread vs Deamon Thread, Main Thread Notion de priorité d'un Thread Deux façons de créer un Thread: extends java.lang.Thread Class Implement java.lang.Runnable Interface 3 / 20
  • 4. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronisation ForkJoin /∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗ OPTION1∗∗∗∗∗∗∗∗∗∗∗∗∗/ public class MonThread extends Thread { public void run() { // Thread behavior goes here !! . . . } } // Start Thread MonTread t1= new MonThread(); t1 . start () ; /∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗ OPTION2∗∗∗∗∗∗∗∗∗∗∗∗∗/ public class MyRunnable implements Runnable { public void run() { // Thread behavior goes here !! . . . } } Thread t2= new Thread ( new MyRunnable()); t2 . start () ; 4 / 20
  • 5. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronisation ForkJoin Problèmes Et le résultat ? retour de la methode run: void gestion des exceptions démarrage du thread synchrone ou asynchrone? 4 / 20
  • 6. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronisation L'interface Callable ForkJoin public Interface Callable<V> java.util.concurrent package, since JDK 1.5 Dénit une unique methode sans argument call. Retourne un résultat Générique V Peut lever une exception 5 / 20
  • 7. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronisation ForkJoin public class MyCallable implements CallableString { } public String call() throws exception { // Thread behavior goes here!! } . . . 6 / 20
  • 9. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Executor ExecutorService Executors Synchronisation ForkJoin Executor L'interface Executor: Découpler la soumission des tâches concurrentes des mécanismes d'exécution de chaque tâche Méthodes fournies void execute(Runnable command) Exécuter la commande passée en paramètre dans le future Futurev submit = executor.submit(worker); ListFutureT invokeAll(Collection? extends CallableT tasks) Lien Future/Callable/Executor Variantes ExecutorService ThreadPoolExeceutor Serial, Parallel, Cache, etcc 7 / 20
  • 10. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Executor ExecutorService Executors Synchronisation ExecutorService ForkJoin ExecutorService: Spécialisation de l'interface Executor an de soumettre des Runnable Callable Collection de Callable Collection de Runnable Sous ensemble de Runnable/Callable 8 / 20
  • 11. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Executor ExecutorService Executors Synchronisation ForkJoin Executors Factory de ThreadPool / Executor Créé un exécuteur ociant avec un seul worker thread et une queue de traitement. static ExecutorService newSingleThreadExecutor() static ExecutorService newFixedThreadPool(int nThreads) pool de Threads faisant usage d'une le de tâches. Pool fonctionnant suivant le sytème de cache nThread static ExecutorService newCachedThreadPool() static ScheduledExecutorService Executeur pouvant lancer des threads périodiques, avec des délais newSingleThreadScheduledExecutor() 9 / 20
  • 12. Threads for the Origin Callable Future ThreadPool Synchronisation 1 Executor ExecutorService Executors Synchronisation ForkJoin public class PoolThreadTest { private static final int NB_TASKS = 100; public static void main(String args[]){ // Execultor service Factory ExecutorService cacheExecutor = Executors.newCachedThreadPool(); ExecutorService singleExecutor = Executors.newSingleThreadExecutor(); ExecutorService fixedExecutor = Executors.newFixedThreadPool(3); // Create a task list CollectionDummyCallable tasks= new 9 / 20
  • 13. Threads executor the Origin Callable Future ThreadPool Synchronisation 1 Executor ExecutorService Executors Synchronisation ForkJoin ArrayList(NB_TASKS); for(int i=0;iNB_TASKS;i++){ t= new DummyCallable(i); tasks.add(t); } DummyCallable //start executor startExecutor(fixedExecutor, tasks); } private static void startExecutor(ExecutorService fixedExecutor, CollectionDummyCallable tasks) { try { ListFutureLong 9 / 20
  • 14. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Executor ExecutorService Executors Synchronisation ForkJoin futures=executor.invokeAll(tasks); executor.awaitTermination(1, TimeUnit.MINUTES); catch (InterruptedException | IllegalStateException e) { e.printStackTrace(); }finally{ executor.shutdown(); System.out.println(bye bye!); } } } 10 / 20
  • 15. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Executor ExecutorService Executors Synchronisation ForkJoin ScheduledExecutorService Exécuter des tâches Après un délai schedule (Callable task, long delay, TimeUnit timeunit) schedule (Runnable task, long delay, TimeUnit timeunit) A une fréquence xe: example toutes les 5min scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit) Avec un délai xe entre la n d'un Run et le début du suivant scheduleWithFixedDelay (Runnable, long initialDelay, long period, TimeUnit timeunit) Comme tous les Executeurs vous devez les arrêter explicitement après usage 10 / 20
  • 16. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronized ReentrantLock ReadWriteLock Synchronisation ForkJoin ScheduledExecutorService ses = Executors.newScheduledThreadPool(5); ScheduledFuture sf = ses.schedule(new Callable() { public Object call() throws Exception { System.out.println(Executed!); return StarTech Java!; } }, 5, TimeUnit.SECONDS); System.out.println(result = + sf.get()); ses.shutdown(); 11 / 20
  • 17. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronized ReentrantLock ReadWriteLock Synchronisation Synchronized ForkJoin Protection de l'accès aux sections critiques Implémentation d'un lock structuré:synchronized methods and synchronized statements Interdit l'exécution concurrente de regions protégées sur un même objet par deux Threads Reentrant mechanism 11 / 20
  • 18. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronized ReentrantLock ReadWriteLock Synchronisation ForkJoin //***********SOLUTION1 public static synchronized Singleton getInstance(){ if (instance==null) //1 instance=new Singleton(); //2 return instance; //3 } //*************SOLUTION2 public static Singleton getInstance(){ if (instance==null) { //1 synchronized (Singleton.class){ //2 instance=new Singleton(); } } return instance; } 11 / 20
  • 19. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronized ReentrantLock ReadWriteLock Synchronisation ForkJoin // Q:which one is correct? A: None Why? 12 / 20
  • 20. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronized ReentrantLock ReadWriteLock Synchronisation Synchronized issues ForkJoin Problèmes Thread automatiquemnt bloqué si le verrou est occupé Pas de vue sur la le des Threads bloqués et reprise après lock Gestion des locks multiples Lock Structuré Unfair Lock No way to check ability to trying for lock interruptibly No delay/timeout waiting period Dierence Read/Write operations 12 / 20
  • 21. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronized ReentrantLock ReadWriteLock Synchronisation ReetrantLock ForkJoin ReetrantLock: Lock Reentrant plus exible Fairness: The most waiting Thread is always choosen if activated Specialisation: ReaderLock and WritterLock Waiting Thread Queue tryLock to check if lock is available : not blockant 13 / 20
  • 22. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronized ReentrantLock ReadWriteLock Synchronisation ReadWriteLock ForkJoin ReadWriteLock: Interface de gestion d'un lock en Lecture/Ecriture Plusieurs Lecteurs autorisés en parallèle Les Rédacteurs sont prioritaires sur les lecteurs En interne: Deux lock séparés ReentrantReadWriteLock implements ReadWriteLock 14 / 20
  • 23. Threads: the Origin Callable Future ThreadPool Synchronisation 1 CountDownLatch CyclicBarrier Phaser Synchronisation ForkJoin ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); readWriteLock.readLock().lock(); // Plusieurs Lecteur peuvent entrer dans cette section // si le verrou n'est pas occupé par un Redacteur, et aucun rédacteur en Attente du verrou readWriteLock.readLock().unlock(); readWriteLock.writeLock().lock(); // seuls les Redacteurs peuvent atteindre cette section, // si aucun lecteur actif. readWriteLock.writeLock().unlock(); 15 / 20
  • 24. Threads: the Origin Callable Future ThreadPool Synchronisation 1 CountDownLatch CyclicBarrier Phaser Synchronisation CountDownLatch ForkJoin Permettre à un ou plusieurs Thread d'attendre la n de l'exécution d'un ensemble d'actions par un ou plusieurs autres Threads un CountDownLatch est initialisé avec un compteur la méthode countDown() décrémente le compteur la méthode await() bloque le Thread appelant jusqu'a ce que le compteur atteigne la valeur zero Tous les Thread bloqués sont libérés lorsque le compteur devient nul le compteur ne peut pas être réinitialisé. Tout appel à await après que le compteur soit passé à zero se termine imédiatement 15 / 20
  • 25. Threads the Origin Callable Future ThreadPool Synchronisation 1 CountDownLatch CyclicBarrier Phaser Synchronisation ForkJoin final CountDownLatch countDownLatch = new CountDownLatch(2); Thread t = new Thread(new Runnable() { public void run() { System.out.println(countDownLatch.getCount()); //(2) countDownLatch.countDown(); System.out.println(countDownLatch.getCount()); //(1) try { Thread.sleep(5000); countDownLatch.countDown(); System.out.println(countDownLatch.getCount()); //(0) } catch (InterruptedException e) { e.printStackTrace(); 15 / 20
  • 26. Threads: the Origin Callable Future ThreadPool Synchronisation 1 CountDownLatch CyclicBarrier Phaser Synchronisation ForkJoin } }); } t.start(); try { countDownLatch.await(); //blocks the current Thread System.out.println(MainThread +countDownLatch.getCount()); // run only when latch=0 } catch (InterruptedException e) { e.printStackTrace(); } 16 / 20
  • 27. Threads: the Origin Callable Future ThreadPool Synchronisation 1 CountDownLatch CyclicBarrier Phaser Synchronisation CyclicBarrier ForkJoin Permettre à un ou plusieurs Thread de s'attendre à un point de rendez vous. un CyclicBarrier est initialisé avec un compteur Contrairement au CountDownLatch, le compteur peut être réinitialisé pour un nouveau cycle: reset la méthode await() bloque le Thread appelant jusqu'a ce que l'une des conditions suivantes soit vériée le compteur atteind la valeur zero naturellement ou par un appel à reset Le Thread appelant est interrompu par un autre Thread un Thread en attente du RDV atteind son timeout Tous les Thread bloqués sont libérés lorsque le compteur devient nul ou le compteur ressetté 16 / 20
  • 28. Threads: the Origin Callable Future ThreadPool Synchronisation 1 CountDownLatch CyclicBarrier Phaser Synchronisation ForkJoin //create a Cyclic Barrier CyclicBarrier barrier = new CyclicBarrier(5); //Make the current thread wait at barrier barrier.await(); //after 15s the Thread is release even if the counter is not 0 barrier.await(15, TimeUnit.SECONDS); //define a barrier action Runnable barrierAction = new Runnable( ... ; CyclicBarrier barrier = new CyclicBarrier(3, barrierAction); 17 / 20
  • 29. Threads: the Origin Callable Future ThreadPool Synchronisation 1 CountDownLatch CyclicBarrier Phaser Synchronisation Phaser ForkJoin Mécanisme de synchornisation à un point de rendez vous similaire au CyclicBarrier Supporte plusieurs cycles, JDK 7 le nombre de parties n'est pas xé à l'avance: dynamique au l du temps et des cycles l'enregistrement se fait à tout moment: methode register Atteindre le point de RDV int arrive() / et se désister du prochain cycle arriveAndDeregister() boolean onAdvance(int phase, int registeredParties), réagir aux changement de cycles int arriveAndAwaitAdvance() attendre les autres Threads au point de rendez vous. 17 / 20
  • 30. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronisation ForkJoin Fork/Join Programmation Multi-Core, DPR algorithm,JSR 166 libs, native in JDK7 ForkJoinPool Fixed Pool Size Thread, if no size specied= Number of available processors ExecutorService permettant d'exécuter des ForkJoinTasks Un Thread peut récupérer une tâche dans la le d'attente d'un autre Thread fork: subdiviser un traitement en plusieurs sous traitements parallèles RecursiveTask RecursiveAction: sous classes de ForkJoinTask join: Récupérer le résultat d'une sous tâche 18 / 20
  • 32. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronisation ForkJoin public class MaxSearchTask extends RecursiveTask{ protected Long compute() { if(sup-inf5){ return simpleMax(); } else{ int mid=(inf+sup)/2; MaxSearchTask search1 = new MaxSearchTask(inf,mid, t); MaxSearchTask search2 = new MaxSearchTask(mid, sup, t); invokeAll(search1,search2); return Math.max((Long)search1.join(),(Long) search2.join()); } ... } 19 / 20
  • 33. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronisation Multithreading is also ForkJoin Types Atomiques, AtomicInteger, AtomicXXX Volatile: The volatile force the thread to update the original variable. Utiliser les collections appropriées en fonction des situations: Thread safe collections vs non Thread safe collections BlockingQueue Outils de proling: JProler, VisualVM, Debugging, JDWP ... 19 / 20
  • 34. Threads: the Origin Callable Future ThreadPool Synchronisation 1 Synchronisation QA ForkJoin Now this is not the end. It is not even the beginning of the end. But it is, perhaps, the end of the beginning. Winston Churchill 20 / 20