Search code examples
javamultithreadingthreadpoolexecutorservicethreadpoolexecutor

newFixedThreadPool() vs newCachedThreadPool()


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.


Solution

  • 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