Thread Pool, concurrency concept.
java.util.concurrent.ThreadPoolExecutor
:
The API documentation :ThreadPoolExecutor. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html
is comprehensive and detailed but difficult to imagine the working flow since there's no diagram or illustration, only descriptive text. But another clue that enlightens me to understand about it is the producer/consumer pattern.
Simply put, tasks are sent from multiple producers into a waiting queue, waiting to be handled by multiple consumers.
https://medium.com/@vipulgupta_19290/threadpool-or-executor-framework-7007844cac52
Initially, there are 2 available threads in the thread pool. The 2 first tasks go through the queue and get redirected to idle Thread 1 and 2 for execution. When task 3 is enqueued, as there’s no available thread, ThreadFactory inside the ThreadPoolExecutor creates a new Thread 3 to handle the task. The same thing happens to task 4 and 5 with the creation of Thread 4 and 5. The maximum thread pool size is now reached, no more thread can be created. Task 6, 7, 8 are enqueued and wait until there’s an available Thread worker to handle. When the queue is full, it rejects any incoming tasks, so task 9 and 10 get blocked and redirected to a fallback function. Notes that if Thread 3, 4 or 5 is idle longer than keepAliveInMinutes period, it will get disposed. The thread pool shrinks its size to 2 (coreSize). In summary, there are 8 tasks get executed and 2 get rejected. That’s it! I hope this article is informative and useful for you. Feel free have any question or concern on the comment section below. Thank you for your time!
ThreadPoolExecutor.png
其中,Worker 的模型如下:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
1、corePoolSize: 规定线程池有几个线程(worker)在运行。 2、maximumPoolSize: 当workQueue满了,不能添加任务的时候,这个参数才会生效。规定线程池最多只能有多少个线程(worker)在执行。 3、keepAliveTime: 超出corePoolSize大小的那些线程的生存时间,这些线程如果长时间没有执行任务并且超过了keepAliveTime设定的时间,就会消亡。 4、unit: 生存时间对于的单位 5、workQueue: 存放任务的队列 6、threadFactory: 创建线程的工厂 7、handler: 当workQueue已经满了,并且线程池线程数已经达到8、maximumPoolSize,将执行拒绝策略。
用户通过submit提交一个任务。线程池会执行如下流程:
https://medium.com/@truongminhtriet96/playing-with-hystrix-thread-pool-c7eebb5b0ddc