3

In case newCachedThreadPool() as per creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available whereas in case of newFixedThreadPool(int size) specify size to create the thread pool with size specified.

Why isn'tnewFixedThreadPool(int size) implemented in newCachedThreadPool() fashion where thread pool creates the new thread only when required and will limit the thread to size?

Any clarrification on the above is really helpful.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Brinal
  • 172
  • 2
  • 18
  • 1
    Related: http://stackoverflow.com/questions/949355/newcachedthreadpool-v-s-newfixedthreadpool – Maroun Apr 14 '15 at 06:35
  • 1
    Because that would not be a **fixed** thread pool anymore. The created thread pools are both instances of ThreadPoolExecutor, created with different options. Creating an starting a new thread takes some time, and you might want that time to be taken at startup, rather than when submitting a new task. – JB Nizet Apr 14 '15 at 06:35
  • @JBNizet Will it not hold the resources in case of fixed thread pool. Its the decision between which is more costlier. Any insight on it. – Brinal Apr 14 '15 at 06:40
  • If you know you'll need a certain number of threads, it's less overhead to create them at the outset, and fail-fast if you can't, rather than doing all the bookkeeping necessary to expire unused threads or determine whether create more threads. – erickson Apr 14 '15 at 06:44

1 Answers1

7

newFixedThreadPool also creates threads lazily. Try this test:

    ThreadPoolExecutor p = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
    System.out.println(p.getPoolSize());
    p.execute(new Runnable() {public void run() {}});
    System.out.println(p.getPoolSize());

The differences are:

  1. newFixedThreadPool's threads never expire, while newCachedThreadPool's threads expire 60 secs after last used
  2. newCacheThreadPool's maximum number of active threads is unlimited
Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275