How to manage orders in which Java Futures is shipped?

In this example, I am sending several files to my comparator object. Everything works fine, except that I noticed that the order in which the files are presented does not always coincide with the order in which they are returned. Any suggestions on how I can better control this?

 ExecutorService pool = Executors.newFixedThreadPool(5);
  CompletionService<Properties> completion = new ExecutorCompletionService<Properties>(pool);

  for (String target : p.getTargetFiles()) {
   completion.submit(new PropertiesLoader(target, p));
  }

  for (@SuppressWarnings("unused")
  String target : p.getTargetFiles()) {
   Properties r = null;
   try {
    r = completion.take().get();
   } catch (InterruptedException e) {
    e.printStackTrace();
   } catch (ExecutionException e) {
    e.printStackTrace();
   }

   p.addTargetFilesProperties(r);
  }

  pool.shutdown();
+3
source share
2 answers

CompletionService.take , , Future , , . , ( CompletionService , ). Future, submit(), .get() ; , .

+3

ThreadPoolExecutor , . , , . , .

- EDIT -

concurrency, , . get(), .

0

Source: https://habr.com/ru/post/1749461/


All Articles