Last active
March 14, 2021 11:12
-
-
Save isopropylcyanide/042f84f07cec4582509b6bf50fb9c6ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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