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.

Comments to: Multi-threading in JAVA using “Executors”

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

Login

Welcome to Typer

Brief and amiable onboarding is the first thing a new user sees in the theme.
Join Typer