Java Executors run tasks that return a result

Introduction

The Executor framework can run concurrent tasks that return a result.

The Java Concurrency API achieves this with the following two interfaces:

  • Callable: This interface has the call() method which has the logic of a task.
  • Future: This interface has methods to get the result from a Callable object and to manage its state.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

class FactorialCalculator implements Callable<Integer> {
  private Integer number;

  public FactorialCalculator(Integer number) {
    this.number = number;
  }/*  w  w  w.j  a v a  2  s.  c  om*/

  @Override
  public Integer call() throws Exception {
    int num, result;
    num = number.intValue();
    result = 1;

    if ((num == 0) || (num == 1)) {
      result = 1;
    } else {
      for (int i = 2; i <= number; i++) {
        result *= i;
        Thread.sleep(20);
      }
    }
    System.out.println(Thread.currentThread().getName() + " " + result);
    return result;
  }
}

public class Main {
  public static void main(String[] args) {
    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
    List<Future<Integer>> resultList = new ArrayList<>();


    for (int i = 0; i < 10; i++) {
      FactorialCalculator calculator = new FactorialCalculator(12);
      Future<Integer> result = executor.submit(calculator);
      resultList.add(result);
    }

    do {
      System.out.println("Main: Number of Completed Tasks:" + " " + executor.getCompletedTaskCount());
      for (int i = 0; i < resultList.size(); i++) {
        Future<Integer> result = resultList.get(i);
        System.out.println("Main: Task:" + " " + i + " " + result.isDone());
      }
      try {
        Thread.sleep(250);
      } catch (Exception e) {
        e.printStackTrace();
      }
    } while (executor.getCompletedTaskCount() < resultList.size());
    
    for (int i = 0; i < resultList.size(); i++) {
      Future<Integer> result = resultList.get(i);
      Integer number = null;
      try {
        number = result.get();
      } catch (Exception e) {
        e.printStackTrace();
      }
      System.out.println("Core: Task" + " " + i + " " + number);
    }
    executor.shutdown();
  }
}



PreviousNext

Related