In this example, i am submitting a few files to my comparator object. It all works fine, except that i noticed that order in which files are submitted is not always teh same 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();
The main point of using
CompletionService.takeis to have it return whicheverFuturehas finished, no matter what order they were submitted. If you want to return them in order you might as well not use that at all (you might not even want to useCompletionServiceat all, but you can). Keep a list of theFutureobjects returned fromsubmit()and call.get()on each one; it will block until the result is available.