Several recent discoveries of the misuse of threadpoolexecutor, including themselves, have been found to be due to a lack of careful reading of annotations and internal workings, taking the guesswork out of parameters, and first looking at the build parameters of a new threadpoolexecutor:
publicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
See this parameter is easy to let people think is the line constructor keep Corepoolsize thread, if not enough, add thread into the pool until maximumpoolsize size, if not enough to workqueue Riga, If Workqueue is not enough to use Rejectedexecutionhandler to do refuse processing.
But this is not the case, the specific process is as follows:
1) Create a new thread when the pool size is less than corepoolsize and process the request
2) When the pool size equals corepoolsize, put the request into the workqueue, the free thread in the pool goes from the Workqueue to take the task and handle
3) When the Workqueue does not fit into the new task, the new thread sinks into the pool and processes the request, and if the pool size is up to maximumpoolsize, use Rejectedexecutionhandler to reject it.
4) In addition, when the number of threads in the pool is greater than corepoolsize, the extra thread waits for KeepAliveTime for a long time and destroys itself if no request can be processed.
The internal structure is as follows:
It can be found that Threadpoolexecutor relies on the blockingqueue blocking mechanism to maintain the thread pool, which is blocked by Workqueue.take () when there is nothing to do in the pool.
Copyright NOTICE: This article for Bo Master original article, without BO Master permission cannot reprint (Contact: QQ312037487 Email: [Email protected]).
In-depth understanding of threadpoolexecutor operation mechanism