1

I wanted to know whether there is a way for increasing number of threads in FixedThreadPool or ScheduledThreadPool when all the threads are in usage. That is for Example1: suppose we take a FixedThreadPool with size say 5, when all the threads are in usage then another task or function which need to be done has to wait for a thread to become free. I need to avoid this and the number of threads has to increase dynamically without using CachedThreadPool. Is there any way in doing so?

Example2:

ScheduledExecutorService execService =  Executors.newScheduledThreadPool(1);

I have limited the number of threads in the above example 2 to 1. Now when this thread is busy in doing some task the other task to be done has to wait right? Now I want like : this fixed number of threads has to increase dynamically. Is there anyway in doing so?

Hema Chandra
  • 363
  • 2
  • 4
  • 16
  • 3
    "without using CachedThreadPool" - Increasing the thread count sounds like cached thread pool, so why not use it? – Fildor Feb 21 '17 at 09:49
  • Please go see http://stackoverflow.com/a/3160266/7573818 – Jeremy Grand Feb 21 '17 at 09:58
  • Possible duplicate of [Can you dynamically resize a java.util.concurrent.ThreadPoolExecutor while it still has tasks waiting](http://stackoverflow.com/questions/2791851/can-you-dynamically-resize-a-java-util-concurrent-threadpoolexecutor-while-it-st) – Jeremy Grand Feb 21 '17 at 09:59

2 Answers2

2

There is actually only one class which implements ScheduledExecutorService called the ScheduledThreadPoolExecutor. This has two parameters to define the number of threads it can have which is the core thread pool (or minimum size) and the maximum thread pool size.

The fixed thread pool factory method creates an instance of this class where the minimum and maximum are the same.

The caches thread pool factory method creates an instance which has a minimum of 0 and no real maximum.

If you want a dynamic thread pool size I suggest you set a high maximum and a minimum you think is appropriate. Whether you create the instance directory or used the fixed/cached thread pool doesn't make much difference.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

ScheduledExecutorService execService = Executors.newScheduledThreadPool(1);

No. Here ScheduledExecutorService will not spawn new threads.

you have to go for newCachedThreadPool

Avaneesh
  • 162
  • 5