FixedThreadPool vs CachedThreadPool: the lesser of two evils

前端 未结 3 1842
庸人自扰
庸人自扰 2020-11-28 01:39

I have a program that spawns threads (~5-150) which perform a bunch of tasks. Originally, I used a FixedThreadPool because this similar question suggested they

3条回答
  •  独厮守ぢ
    2020-11-28 02:12

    Both FixedThreadPool and CachedThreadPool are evils in highly loaded applications.

    CachedThreadPool is more dangerous than FixedThreadPool

    If your application is highly loaded & demands low latency, better to get rid of both options due to below drawbacks

    1. Unbounded nature of task queue : It may cause out of memory or high latency
    2. Long running threads will cause CachedThreadPool to go out of control on Thread creation

    Since you know that both are evils, lesser evil doesn't do any good. Prefer ThreadPoolExecutor, which provides granular control on many parameters.

    1. Set the task queue as bounded queue to have better control
    2. Have right RejectionHandler - Your own RejectionHandler or Default handlers provided by JDK
    3. If you have something to do on before/after completion of task, override beforeExecute(Thread, Runnable) and afterExecute(Runnable, Throwable)
    4. Override ThreadFactory, if thread customization is required
    5. Control Thread pool size dynamically at run time ( related SE question : Dynamic Thread Pool)

提交回复
热议问题