How to decide whether to use newCachedThreadPool or newFixedThreadPool?

随声附和 提交于 2019-12-02 20:31:01

So now I am wondering is - Should I use newFixedThreadPool or newCachedThreadPool in my code?

To quote from the Javadocs, the newFixedThreadPool():

Creates a thread pool that reuses a fixed number of threads...

This means that if you ask for 2 threads, it will start 2 threads and never start 3. On the other hand, the newCachedThreadPool():

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.

In your case, if you only have 2 thread to run, either will work fine since you will only be submitting 2 jobs to your pool. However, if you wanted to submit all 20 jobs at once but only have 2 jobs running at one time, you should use a newFixedThreadPool(2). If you used a cached pool then each of the 20 jobs will start a thread which will run at the same time which may not be optimal depending on how many CPUs you have.

Typically I use the newCachedThreadPool() when I need the thread to be spawned immediately, even if all of the threads currently running are busy. I recently used it when I was spawning timer tasks. The number of concurrent jobs are immaterial because I never spawn very many but I want them to run when they are requested and I want them to re-use dormant threads.

I used newFixedThreadPool() when I want to limit the number of concurrent tasks running at any one point to maximize performance and not swamp my server. For example if I am processing 100k lines from a file, one line at a time, I don't want each line to start a new thread but I want some level of concurrency so I allocate (for example) 10 fixed threads to run the tasks until the pool is exhausted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!