In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is a thread pool". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is a thread pool".
1. Core class of thread pool: ThreadPoolExecutor1.1- class diagram (I: for interface, C: for implementation class) I:Executor I:ExecutorService C:AbstractExecutorService C:ThreadPoolExecutor
The main constructors of this class are as follows:
Public ThreadPoolExecutor (int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit, BlockingQueue workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler); 1.2-detailed explanation of parameters:
CorePoolSize: the size of the core thread pool. If there is a free location in the core thread pool, the new task will be executed by a new thread in the core thread pool. After execution, the thread will not be destroyed, and the thread will enter the cache queue and wait to be run again.
MaximunPoolSize: the maximum number of threads. If the core thread pool and cache queue are full, new tasks come in and new threads are created to execute. However, the quantity cannot exceed maximunPoolSize, otherwise the side will adopt the strategy of rejecting the task, which we will analyze in detail below.
KeepAliveTime: the maximum amount of time that a non-core thread can be idle, after which the thread terminates. This parameter works by default only if the number of threads exceeds the core thread pool size. As long as the number of threads does not exceed the core thread size, it will not work.
Unit: unit of time, used with keepAliveTime.
WorkQueue: cache queue, which is used to store tasks waiting to be executed. The following values are available:
1. ArrayBlockingQueue; bounded blocking queue. For more information, please see the article: ArrayBlockingQueue details
2. LinkedBlockingQueue; unbounded blocking queue. For more information, please see the article: LinkedBlockingQueue details
3. SynchronousQueue; unbuffered blocking queue. For more information, please see article: SynchronousQueue details
ThreadFactory: thread factory, used to create threads, default new Executors.DefaultThreadFactory ()
Handler: thread rejection policy. When the created thread exceeds the maximumPoolSize value and the buffer queue is full, the processing strategy for the newly submitted task has the following four values. We combine code analysis.
1. ThreadPoolExecutor.AbortPolicy ignores the task (that is, discards the task) and tells the caller "I refuse to accept the new task" by throwing an exception.
Public void rejectedExecution (Runnable r, ThreadPoolExecutor e) {/ / throws an exception directly here, which can be understood as ignoring the task (that is, discarding the task) and telling the caller that "I refuse to accept the new task" throw new RejectedExecutionException ("Task" + r.toString () + "rejected from" + e.toString ());}
2. ThreadPoolExecutor.DiscardPolicy: also discard the task, but do not do any processing.
Public void rejectedExecution (Runnable r, ThreadPoolExecutor e) {/ / here is the empty implementation, that is, the task is discarded without any processing / / this will lead to: although this policy is triggered, the caller has no idea whether the task submitted by it has been executed or not.
3. ThreadPoolExecutor.DiscardOldestPolicy: discard the first task in the queue and try to execute the new task.
Public void rejectedExecution (Runnable r, ThreadPoolExecutor e) {if (! e.isShutdown ()) {/ / determine whether the thread pool is closed e.getQueue (). Poll (); / discard the first task in the queue e.execute (r); / / try to execute a new task}}
4. ThreadPoolExecutor.CallerRunsPolicy: the task is handled by the calling thread
Public void rejectedExecution (Runnable r, ThreadPoolExecutor e) {if (! e.isShutdown ()) {/ / determine whether the thread pool is closed r.run (); / / the calling thread directly calls the run () method to execute its code logic}}
1.3-Executors factory class
There are so many construction parameters based on ThreadPoolExecutor that JDK provides us with the Executors class, through which we can simply create four types of thread pools, which are sufficient in general scenarios.
1.3.1, fixed size thread pool
Public static ExecutorService newFixedThreadPool (int nThreads) {return new ThreadPoolExecutor (nThreads,// corePoolSize nThreads,// maximumPoolSize 0L, TimeUnit.MILLISECONDS,// keepAliveTime=0 seconds new LinkedBlockingQueue () / / using unbounded blocking queues);}
Parameters: corePoolSize = fixed value, maximumPoolSize = fixed value, keepAliveTime = 0 seconds, workQueue = LinkedBlockingQueue unbounded blocking queue
Analysis:
1. Both corePoolSize and maximumPoolSize are fixed values of nThreads, indicating that there are all core threads in this thread pool, keepAliveTime is the idle time of non-core threads, and there are no non-core threads in the thread pool, so the parameter keepAliveTime is invalid here.
2. New LinkedBlockingQueue (): an unbounded blocking queue used in the cache queue. When the threads in the core pool are busy, the new tasks are placed in this queue; once there are idle threads, the thread will take the task execution from the queue.
3. Disadvantages: because unbounded queues are used, when nThreads threads are occupied all the time, while new tasks keep coming in, it may lead to OOM problems.
1.3.2, thread pool for a single thread
Public static ExecutorService newSingleThreadExecutor () {return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor (1,1, / / corePoolSize,maximumPoolSize 0L, TimeUnit.MILLISECONDS) / / keepAliveTime=0 second new LinkedBlockingQueue () / / using unbounded blocking queue) }
Parameter: corePoolSize = 1MaximumPoolSize = 1memmemAliveTime = 0 seconds, workQueue = LinkedBlockingQueue unbounded blocking queue
Analysis:
1. Both corePoolSize and maximumPoolSize are 1, and there is only one core thread in this thread pool. As above, the parameter keepAliveTime is invalid here.
2. New LinkedBlockingQueue (): an unbounded blocking queue used in the cache queue. When only one core thread is busy, new tasks are placed in this queue. When the thread is idle, it will take the task execution from the queue.
3. Disadvantages: because unbounded queues are used, when the core thread has been occupied all the time, while new tasks are constantly coming in, it may lead to OOM problems.
4. Have you noticed why a FinalizableDelegatedExecutorService class is used here?
See article: analysis of FinalizableDelegatedExecutorService source code in newSingleThreadExecutor
1.3.3. Cache thread pool
Public static ExecutorService newCachedThreadPool () {return new ThreadPoolExecutor (0, Integer.MAX_VALUE,// corePoolSize,maximumPoolSize 60L, TimeUnit.SECONDS,// keepAliveTime=60 second new SynchronousQueue ()); / / synchronous blocking queue}
Parameter: corePoolSize = 0MaximumPoolSize = infinite, keepAliveTime = 60 seconds (important), workQueue = SynchronousQueue unbuffered blocking queue
Analysis: a thread pool that can create threads as needed. All threads in this thread pool are non-core threads with a maximum idle time of 60 seconds, and a maximum of Integer.MAX_VALUE threads can be created (2 ^ 31 power, more than 2.1 billion, which can be regarded as infinite). SynchronousQueue is an unbuffered blocking queue, that is, no new tasks are buffered in this queue. When new tasks come in, if there are no idle threads, a new thread will be created If there are free threads, free threads are used; so this thread pool is suitable for performing tasks with short execution cycles.
Thank you for your reading, the above is the content of "what is a thread pool", after the study of this article, I believe you have a deeper understanding of what is a thread pool, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.