Browser docs

Thread Pool

Intent

It is often the case that tasks to be executed are short-lived and the number of tasks is large. Creating a new thread for each task would make the system spend more time creating and destroying the threads than executing the actual tasks. Thread Pool solves this problem by reusing existing threads and eliminating the latency of creating new threads.

Explanation

Real-world example

We have a large number of relatively short tasks at hand. We need to peel huge amounts of potatoes and serve a mighty amount of coffee cups. Creating a new thread for each task would be a waste so we establish a thread pool.

In plain words

Thread Pool is a concurrency pattern where threads are allocated once and reused between tasks.

Wikipedia says

In computer programming, a thread pool is a software design pattern for achieving concurrency of execution in a computer program. Often also called a replicated workers or worker-crew model, a thread pool maintains multiple threads waiting for tasks to be allocated for concurrent execution by the supervising program. By maintaining a pool of threads, the model increases performance and avoids latency in execution due to frequent creation and destruction of threads for short-lived tasks. The number of available threads is tuned to the computing resources available to the program, such as a parallel task queue after completion of execution.

Programmatic Example

Let’s first look at our task hierarchy. We have a base class and then concrete CoffeeMakingTask and PotatoPeelingTask.

 1public abstract class Task {
 2
 3  private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
 4
 5  private final int id;
 6  private final int timeMs;
 7
 8  public Task(final int timeMs) {
 9    this.id = ID_GENERATOR.incrementAndGet();
10    this.timeMs = timeMs;
11  }
12
13  public int getId() {
14    return id;
15  }
16
17  public int getTimeMs() {
18    return timeMs;
19  }
20
21  @Override
22  public String toString() {
23    return String.format("id=%d timeMs=%d", id, timeMs);
24  }
25}
26
27public class CoffeeMakingTask extends Task {
28
29  private static final int TIME_PER_CUP = 100;
30
31  public CoffeeMakingTask(int numCups) {
32    super(numCups * TIME_PER_CUP);
33  }
34
35  @Override
36  public String toString() {
37    return String.format("%s %s", this.getClass().getSimpleName(), super.toString());
38  }
39}
40
41public class PotatoPeelingTask extends Task {
42
43  private static final int TIME_PER_POTATO = 200;
44
45  public PotatoPeelingTask(int numPotatoes) {
46    super(numPotatoes * TIME_PER_POTATO);
47  }
48
49  @Override
50  public String toString() {
51    return String.format("%s %s", this.getClass().getSimpleName(), super.toString());
52  }
53}

Next, we present a runnable Worker class that the thread pool will utilize to handle all the potato peeling and coffee making.

 1@Slf4j
 2public class Worker implements Runnable {
 3
 4  private final Task task;
 5
 6  public Worker(final Task task) {
 7    this.task = task;
 8  }
 9
10  @Override
11  public void run() {
12    LOGGER.info("{} processing {}", Thread.currentThread().getName(), task.toString());
13    try {
14      Thread.sleep(task.getTimeMs());
15    } catch (InterruptedException e) {
16      e.printStackTrace();
17    }
18  }
19}

Now we are ready to show the full example in action.

 1    LOGGER.info("Program started");
 2
 3    // Create a list of tasks to be executed
 4    var tasks = List.of(
 5        new PotatoPeelingTask(3),
 6        new PotatoPeelingTask(6),
 7        new CoffeeMakingTask(2),
 8        new CoffeeMakingTask(6),
 9        new PotatoPeelingTask(4),
10        new CoffeeMakingTask(2),
11        new PotatoPeelingTask(4),
12        new CoffeeMakingTask(9),
13        new PotatoPeelingTask(3),
14        new CoffeeMakingTask(2),
15        new PotatoPeelingTask(4),
16        new CoffeeMakingTask(2),
17        new CoffeeMakingTask(7),
18        new PotatoPeelingTask(4),
19        new PotatoPeelingTask(5));
20
21    // Creates a thread pool that reuses a fixed number of threads operating off a shared
22    // unbounded queue. At any point, at most nThreads threads will be active processing
23    // tasks. If additional tasks are submitted when all threads are active, they will wait
24    // in the queue until a thread is available.
25    var executor = Executors.newFixedThreadPool(3);
26
27    // Allocate new worker for each task
28    // The worker is executed when a thread becomes
29    // available in the thread pool
30    tasks.stream().map(Worker::new).forEach(executor::execute);
31    // All tasks were executed, now shutdown
32    executor.shutdown();
33    while (!executor.isTerminated()) {
34      Thread.yield();
35    }
36    LOGGER.info("Program finished");

Class diagram

alt text

Applicability

Use the Thread Pool pattern when

  • You have a large number of short-lived tasks to be executed in parallel

Credits