# sizing thread pooljava
Thread pool size should rarely be hard-coded, instead it should be provided by configuration mechanism or computed dynamically.
api
If size 'too big', threads compete for scare CPU and memory resources, resulting in possible resources exhaustion.
ide
If size 'too small', throughput suffers.this
The optimal pool size is:code
size = N(cpu) * U(cpu) * (1 + wait time / compute time)
ci
U(cpu): target CPU utilization[0,1]get
int N_CPUS= Runtime.getRuntime().availableProcessors();
# ThreadPoolExecutorrequests
ThreadPoolExecutor provides the base implementation for executors returned by below methods:it
Executors.newSingleThreadExecutor(); Executors.newFixedThreadPool(3); Executors.newCachedThreadPool();
we can instantiate ThreadPoolExecutor through its constructor:
io
ThreadPoolExecutor pool = new ThreadPoolExecutor( /*corePoolSize*/ 5 , /*maximumPoolSize*/ 10, /*keepAliveTime*/ 60L, /*unit*/ TimeUnit.SECONDS, /*workQueue*/ new ArrayBlockingQueue<Runnable>(20), /*threadFactory*/ new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r); } }, /*handler*/ new ThreadPoolExecutor.CallerRunsPolicy());
- corePoolSize: is the target size, we will maintain this size even there are no tasks to execute.
- maximumPoolSize: is the upper bound on how many threads can be active at once.
- keepAliveTime: a thread has been idle for longer than this time becomes a candidate for reaping.
- workQueue: BlockingQueue to hold tasks awaiting execution.
# managing queued tasks
If the arrival rate for new requests exceeds the rate at which they can be handled, requests will queue up.
# saturation polies
when workqueue is full and there is still new requests arrive, saturation policies come into play:
AbortPolicy: default one; throws 'RejectedExecutionException'
DiscardPolicy: silently discards newly submitted task.
DiscardOldestPolicy: discard next task.
CallerRunsPolicy: push back tasks to the caller(main thread, TCP layer, client ..)