Java Programming Tutorials

Java programming tutorials with many code examples!

Java Cached Thread Pool


How and when use Java Cached Thread Pool? In the previous post we’ve shown how Fixed Thread Pool works. In the current example we’ll show how ExecutorService behaves when using Cached Thread Pool.


Executors class from java.util.concurrent package has two helper methods that allows to create executors with cached thread pools:

  • ExecutorService newCachedThreadPool()
    Creates a thread pool that will create new threads when needed and reuse existing, while they are in the cache.
  • ExecutorService newCachedThreadPool(ThreadFactory threadFactory)
    It’s like the above method, but allows to construct threads in own way.

What’s important the cache keeps unused threads for 60 seconds, after which they are removed. So after sometime of inactivity no resources are used.


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class CachedThreadPoolExecutorExample {

    private static class Counter implements Runnable {

        private static int nth = 0;

        private final int id = ++nth;
        private final int number;

        public Counter(int number) {
            this.number = number;

        public void run() {
            System.out.println("Starting counter: " + id);
            for (int i = 0; i < number; ++i) {
                try {
                } catch (InterruptedException e) {
                    // ignore
                System.out.printf("counter %d, value: %d%n", id, i);
            System.out.println("Finishing counter: " + id);

    public static void main(String&#91;&#93; args) {
        System.out.println("Starting Cached Thread Pool");
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 1; i <= 4; ++i) {
            executor.execute(new Counter(3));

<p> And the result of running the example: </p>

Starting Cached Thread Pool
Starting counter: 1
Starting counter: 2
Starting counter: 3
Starting counter: 4
counter 1, value: 0
counter 4, value: 0
counter 3, value: 0
counter 2, value: 0
counter 1, value: 1
counter 4, value: 1
counter 3, value: 1
counter 2, value: 1
counter 1, value: 2
counter 3, value: 2
counter 2, value: 2
Finishing counter: 2
counter 4, value: 2
Finishing counter: 4
Finishing counter: 1
Finishing counter: 3

The output clearly shows that the executor immediately starts as many threads as there are needed to handle submitted tasks.

Cached Thread Pool Executor is a good fit when developing a program or it creates short lived threads. The pool has a drawback of allocating thread resources when a new thread is needed, so when fast task handling is needed better use fixed pools. Also remember about number of allowed threads limit!

Was it helpful? Share!