
17 Jul Multi-threading in JAVA using “Executors”
Multi-threading is not always super easy to implement. There is Runnable, Thread, and all sorts of frameworks/packages but we love the executors class to run our code in threads.
Here is the code:
A time consuming function such as an API call, download files etc.
public Double someTimeConsumingFunction() throws InterruptedException { log.info("Thread started");
Thread.sleep(1000);
log.info("Thread finished");
return Math.random();
}
Our multi-threaded function
public void threadsExample() {
ExecutorService taskExecutor = Executors.newFixedThreadPool(25);
List<Future<Double>> resultList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future<Double> result = taskExecutor
.submit(new Callable<Double>() {
public Double call() {
try {
return someTimeConsumingFunction();
} catch (Exception e) {
log.error(e);
}
return null;
}
});
resultList.add(result);
}
taskExecutor.shutdown();
try {
log.info("Waiting for all threads to finish and terminate");
taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
Sentry.capture(e);
}
log.info("Finished execution");
}
As simple as that. I have actually bookmarked this page as I keep using this code again and again. Let me know in the comments if anything is unclear.
No Comments