Skip to content

Instantly share code, notes, and snippets.

@isopropylcyanide
Last active March 14, 2021 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isopropylcyanide/042f84f07cec4582509b6bf50fb9c6ed to your computer and use it in GitHub Desktop.
Save isopropylcyanide/042f84f07cec4582509b6bf50fb9c6ed to your computer and use it in GitHub Desktop.
public class WorkExecutor {
private final MathService mathService;
public List<Integer> processExpensiveFunction(List<Integer> inputs, int firstK) {
try {
List<Integer> outputs = new ArrayList<>();
//our basic executor
ExecutorService executor = Executors.newCachedThreadPool();
ExecutorCompletionService<Integer> executorService = new ExecutorCompletionService<>(executor);
for (Integer input : inputs) {
executorService.submit(() -> {
//submitting input
log.info("Submitting task f({}) on {}", input, Thread.currentThread().getName());
return mathService.process(input);
});
}
executor.shutdown(); //prevent more tasks
for (int outputCount = 1; outputCount <= firstK; outputCount++) {
//process results as and when they are being executed.
Integer output = executorService.take().get();
log.info("Finished {}/{}: {} on {}", outputCount, firstK, output, Thread.currentThread().getName());
outputs.add(output);
}
return outputs;
} catch (Exception ex) {
log.error("Error processing expensive function");
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment