JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Java newCachedThreadPool Example

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.
Example:
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.

.