Java newCachedThreadPool Example

In this tutorial, we will learn about Executor’s newCachedThreadPool factory method.
In the last tutorial, I have shared introduction to ThreadPoolExecutor. If you are not aware of concepts of ThreadPoolExecutor, you should go through that first.

Executor’s newCachedThreadPool  factory method :

This method returns an unbounded thread pool. It sets maximum pool size to Integer.Max and it will create new threads depending on demand. If demand decreases, it will tear down threads if threads are idle for more than 1 min.


Let’s create a Task. Here Task will be to read different files and process them.

Let’s create ThreadPoolExecutor which will consume above task and process it.

When you run above program, you will get below output:

If you notice, we have submitted 10 tasks and it has created 10 new threads depending on demand.If any thread remains idle for more than one minute, it will tear it down. newCachedThreadPool is a good choice when you want better queuing performance than newFixedThreadPool. If you want to restrict number of concurrent task for resource management, go with newFixedThreadPool.

Add Comment