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.

💻 Awesome Tech Resources:
  • Looking for ⚒️ tech jobs? Go to our job portal.
  • Looking for tech events? Go to tech events 🗓️ Calendar.️

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.


You may also like:

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.