API java : ExecutorCompletionService


java.util.concurrent
Class ExecutorCompletionService<V>

java.lang.Object
  extended by java.util.concurrent.ExecutorCompletionService<V>
All Implemented Interfaces:
CompletionService<V>

public class ExecutorCompletionService<V>
extends Object
implements CompletionService<V>

A CompletionService that uses a supplied Executor to execute tasks. This class arranges that submitted tasks are, upon completion, placed on a queue accessible using take. The class is lightweight enough to be suitable for transient use when processing groups of tasks.

Usage Examples. Suppose you have a set of solvers for a certain problem, each returning a value of some type Result, and would like to run them concurrently, processing the results of each of them that return a non-null value, in some method use(Result r). You could write this as:

  1. void solve(Executor e, Collection<Callable<Result>> solvers)
  2. for (Callable<Result> s : solvers)
  3. ecs.submit(s);
  4. int n = solvers.size();
  5. for (int i = 0; i < n; ++i) {
  6. Result r = ecs.take().get();
  7. if (r != null)
  8. use(r);
  9. }
  10. }
Suppose instead that you would like to use the first non-null result of the set of tasks, ignoring any that encounter exceptions, and cancelling all other tasks when the first one is ready:
  1. void solve(Executor e, Collection<Callable<Result>> solvers)
  2. int n = solvers.size();
  3. List<Future<Result>> futures = new ArrayList<Future<Result>>(n);
  4. Result result = null;
  5. try {
  6. for (Callable<Result> s : solvers)
  7. futures.add(ecs.submit(s));
  8. for (int i = 0; i < n; ++i) {
  9. try {
  10. Result r = ecs.take().get();
  11. if (r != null) {
  12. result = r;
  13. break;
  14. }
  15. } catch(ExecutionException ignore) {}
  16. }
  17. }
  18. finally {
  19. for (Future<Result> f : futures)
  20. f.cancel(true);
  21. }
  22.  
  23. if (result != null)
  24. use(result);
  25. }


Constructor Summary
ExecutorCompletionService(Executor executor)
          Creates an ExecutorCompletionService using the supplied executor for base task execution and a LinkedBlockingQueue as a completion queue.
ExecutorCompletionService(Executor executor, BlockingQueue<Future<V>> completionQueue)
          Creates an ExecutorCompletionService using the supplied executor for base task execution and the supplied queue as its completion queue.
 
Method Summary
 Future<V> poll()
          Retrieves and removes the Future representing the next completed task or null if none are present.
 Future<V> poll(long timeout, TimeUnit unit)
          Retrieves and removes the Future representing the next completed task, waiting if necessary up to the specified wait time if none are yet present.
 Future<V> submit(Callable<V> task)
          Submits a value-returning task for execution and returns a Future representing the pending results of the task.
 Future<V> submit(Runnable task, V result)
          Submits a Runnable task for execution and returns a Future representing that task.Upon completion, this task may be taken or polled.
 Future<V> take()
          Retrieves and removes the Future representing the next completed task, waiting if none are yet present.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ExecutorCompletionService

public ExecutorCompletionService(Executor executor)
Creates an ExecutorCompletionService using the supplied executor for base task execution and a LinkedBlockingQueue as a completion queue.

Parameters:
executor - the executor to use
Throws:
NullPointerException - if executor is null

ExecutorCompletionService

public ExecutorCompletionService(Executor executor,
                                 BlockingQueue<Future<V>> completionQueue)
Creates an ExecutorCompletionService using the supplied executor for base task execution and the supplied queue as its completion queue.

Parameters:
executor - the executor to use
completionQueue - the queue to use as the completion queue normally one dedicated for use by this service
Throws:
NullPointerException - if executor or completionQueue are null
Method Detail

submit

public Future<V> submit(Callable<V> task)
Description copied from interface: CompletionService
Submits a value-returning task for execution and returns a Future representing the pending results of the task. Upon completion, this task may be taken or polled.

Specified by:
submit in interface CompletionService<V>
Parameters:
task - the task to submit
Returns:
a Future representing pending completion of the task

submit

public Future<V> submit(Runnable task,
                        V result)
Description copied from interface: CompletionService
Submits a Runnable task for execution and returns a Future representing that task.Upon completion, this task may be taken or polled.

Specified by:
submit in interface CompletionService<V>
Parameters:
task - the task to submit
result - the result to return upon successful completion
Returns:
a Future representing pending completion of the task, and whose get() method will return the given result value upon completion

take

public Future<V> take()
               throws InterruptedException
Description copied from interface: CompletionService
Retrieves and removes the Future representing the next completed task, waiting if none are yet present.

Specified by:
take in interface CompletionService<V>
Returns:
the Future representing the next completed task
Throws:
InterruptedException - if interrupted while waiting.

poll

public Future<V> poll()
Description copied from interface: CompletionService
Retrieves and removes the Future representing the next completed task or null if none are present.

Specified by:
poll in interface CompletionService<V>
Returns:
the Future representing the next completed task, or null if none are present.

poll

public Future<V> poll(long timeout,
                      TimeUnit unit)
               throws InterruptedException
Description copied from interface: CompletionService
Retrieves and removes the Future representing the next completed task, waiting if necessary up to the specified wait time if none are yet present.

Specified by:
poll in interface CompletionService<V>
Parameters:
timeout - how long to wait before giving up, in units of unit
unit - a TimeUnit determining how to interpret the timeout parameter
Returns:
the Future representing the next completed task or null if the specified waiting time elapses before one is present.
Throws:
InterruptedException - if interrupted while waiting.

Ces informations proviennent du site de http://java.sun.com

Remarques

Contenu

Le contenu de cette page provient du site de Sun, et est généré depuis un cache sur l'infobrol après certains traitements automatisés. La présentation peut donc différer du document original, mais le contenu aussi. Vous pouvez utiliser ce bouton pour afficher la page originale du site de Sun :

Quels sont les motivations de cette démarche?

Maintenir les pages en cache sur différents sites peut offrir plus de disponibilité.

Chaque page est indexée dans la base de donnée, ce qui permet de retrouver facilement les informations, au moyen des sommaires, du moteur de recherche interne, etc.

Des facilités sont mises en place pour que les membres de l'infobrol puissent effectuer des traductions en français des différents documents. Ceci devrait permettre aux débutants en programmation Java de consulter les API en français s'ils maîtrisent moins bien la langue de Shakespeare. Dans le cas où une traduction a été soumise, elle est disponible au moyen d'un lien en bas de page. Si la traduction a été validée, la page s'affiche par défaut en français, et un lien en bas de page permet d'atteindre la version en anglais.

Le code sur l'infobrol est automatiquement coloré selon la syntaxe, et les différents mots clés sont transformés en liens pour accéder rapidement aux informations.

Vous avez la possibilité de partager vos expériences en proposant vos propres extraits de code en utilisant le bouton "ajouter un commentaire" en bas de page. Si vous visitez simplement l'infobrol, vous avez déjà accès à cette fonction, mais si vous étes membre du brol, vous pouvez en plus utiliser des boutons supplémentaires de mise en forme, dont la coloration automatique de vos extraits de codes.

Réseaux sociaux

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher les interactions avec les réseaux sociaux sur ces pages.

 

Nuage de mots clés

7 mots clés dont 0 définis manuellement (plus d'information...).

Avertissement

Cette page ne possède pas encore de mots clés manuels, ceci est donc un exemple automatique (les niveaux de pertinence sont fictifs, mais les liens sont valables). Pour tester le nuage avec une page qui contient des mots définis manuellement, vous pouvez cliquer ici.

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher le nuage de mots clés.

 

Astuce pour imprimer les couleurs des cellules de tableaux : http://www.gaudry.be/ast-rf-450.html
Aucun commentaire pour cette page

© Ce document issu de l′infobrol est enregistré sous le certificat Cyber PrInterDeposit Digital Numbertection. Enregistrement IDDN n° 5329-8833
Document créé le 07/12/06 03:16, dernière modification le Vendredi 17 Juin 2011, 12:12
Source du document imprimé : http://www.gaudry.be/java-api-rf-java/util/concurrent/ExecutorCompletionService.html Document affiché 1 fois ce mois de Juin.
St.Gaudry©07.01.02
Outils (masquer)
||
Recherche (afficher)
Recherche :

Utilisateur (masquer)
Navigation (masquer)
Apparence (afficher)
Stats (afficher)
15832 documents
452 astuces.
549 niouzes.
3099 definitions.
447 membres.
8115 messages.

Document genere en :
0,67 seconde

Mises à jour :
Mises à jour du site
Citation (masquer)
Je sais que mes droits s'arrêtent là où commencent ceux des autres. Mais est-ce ma faute si les droits des autres commencent si loin ?

Mafalda
 
l'infobrol
Nous sommes le Vendredi 01 Juin 2012, 19:58, toutes les heures sont au format GMT+1.00 Heure, heure d'été (+1)