Java - Executor's Completion Service

Description

Executor's Completion Service

Demo

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class TaskResult {
  private int taskId;
  private int result;

  public TaskResult(int taskId, int result) {
    this.taskId = taskId;
    this.result = result;
  }/*from w  w w  .j a  v a2  s  . co m*/

  public int getTaskId() {
    return taskId;
  }

  public int getResult() {
    return result;
  }

  public String toString() {
    return "Task Name: Task #" + taskId + ", Task Result:" + result
        + " seconds";
  }
}

class MyTask implements Callable<TaskResult> {
  private int taskId;
  private int loopCounter;
  public MyTask(int taskId, int loopCounter) {
    this.taskId = taskId;
    this.loopCounter = loopCounter;
  }

  public TaskResult call() throws InterruptedException {
    int totalSleepTime = 0;
    for (int i = 1; i <= loopCounter; i++) {
      int sleepTime = i + 1;
      System.out.println("Task #" + this.taskId + " - Iteration #" + i
          + " is going to sleep for " + sleepTime + " seconds.");
      Thread.sleep(sleepTime * 1000);
      totalSleepTime = totalSleepTime + sleepTime;
    }

    return new TaskResult(taskId, totalSleepTime);
  }
}

public class Main {
  public static void main(String[] args) throws Exception {
    ExecutorService exec = Executors.newFixedThreadPool(3);
    ExecutorCompletionService<TaskResult> completionService = new ExecutorCompletionService<>(
        exec);

    for (int i = 1; i <= 5; i++) {
      MyTask task = new MyTask(i, 3);
      completionService.submit(task);
    }
    Thread.sleep(3000);
    for (int i = 1; i <= 5; i++) {
      Future<TaskResult> completedTask = completionService.take();
      TaskResult result = completedTask.get();
      System.out.println("Completed a task - " + result);
    }
    exec.shutdown();
  }
}

Result

Related Topic