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 {"Thread started");
  Thread.sleep(1000);"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) {
            return null;
  try {"Waiting for all threads to finish and terminate");
    taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
  } catch (InterruptedException e) {
  }"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

Post A Comment