In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "Java concurrency how to use thread pool", in daily operation, I believe many people in Java concurrency how to use thread pool problems have doubts, Xiaobian consulted all kinds of information, sorted out simple and easy to use operation methods, I hope to answer "Java concurrency how to use thread pool" doubts helpful! Next, please follow the small series to learn together!
The role of thread pools
Pooling technology is a very common computer technology, mainly for reuse and improve performance, such as memory pool, connection pool, object pool and so on. Thread pools are no exception, and their main roles are as follows:
Improved performance: thread reuse in the thread pool can significantly reduce the overhead of frequent thread creation and destruction.
Reuse and management: It is convenient to manage and reuse threads in the pool to avoid creating a large number of threads in the production environment.
Decoupling: only expose the interface of submitting tasks, and decouple the creation and destruction of thread pools from business.
JDK defines a set of Executor framework for us in the concurrency package to help developers effectively control threads. There are basic thread pool classes and thread pool factories, but the most important thing is ThreaPoolExecutor, which is also the most frequently asked knowledge point in interviews. This paper focuses on the principle of ThreaPool Executor.
Thread pool parameter description
ThreaPoolExecutor( int corePoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) )
The ThreaPoolExecutor parameter has the following meaning
corePoolSize: Number of core threads in the thread pool.
maximumPoolSize: Maximum number of threads in the thread pool.
keepAliveTime: The time to live of excess idle threads when the thread pool exceeds corePoolSize. That is, how long idle threads exceeding coolPoolSize will be destroyed.
unit: keepAliveTime unit, can be hours, minutes, seconds and other values.
workQueue: A queue of tasks submitted but not yet executed.
threadFactory: thread factory, used to create threads, generally by default.
handler: Rejection policy, how to reject tasks when the thread pool cannot handle them.
workQueue, threadFactory and handler are relatively complex and need to be introduced separately. ThreadFactory and RejectedExecutionHandler are mainly introduced below.
1. Thread Factory: ThreadFactory
Threads in the thread pool are created by the thread factory defined by TrheadFactory, which is an interface with only Thread newThread(Runnable r) method to create threads. Although it is not necessary to specify this parameter when creating ThreadPoolExecutor, Alibaba Coding Specification recommends that it is best to specify this parameter, which has the following advantages:
Track when and how many threads are created in the thread pool.
You can customize the name, group, and priority of the thread pool.
Set other states of the thread, such as daemons.
2. Rejection Policy: RejectedExecutionHandler
When the number of threads in the thread pool reaches maxPoolSize, submitting new tasks enforces a rejection policy. JDK defines four rejection policies:
AbortPolicy This policy throws an exception directly
CallerRunsPolicy calls threads to process tasks. This policy does not really discard tasks. It allows the current thread to execute discarded tasks. Since there is only one thread, all tasks are executed serially.
DiscardOldestPolicy Discards the oldest request, i.e. the task at the head of the queue that is about to be executed, and attempts to submit the current task again.
DiscardPolicy This policy silently discards tasks that cannot be processed.
All four reject policies inherit the interface RejectedExecutionHandler and implement the rejectedExecution(Runnable r, ThreadPoolExecutor executor) method of the interface. If the above four rejection policies do not meet your needs, you can customize the rejection policy, inherit the interface RejectedExecutionHandler and implement the method.
Scheduling logic for thread pools
ThreaPoolExecutor handles the submitted tasks logically as shown below.
1. When submitting a mandate:
If the number of threads in the thread pool is less than the corePoolSize (regardless of whether there are idle threads), a new thread (called a core thread) is created to process.
If the number of threads in the thread pool is already greater than or corePoolSize, the newly submitted task is placed in a waiting queue for scheduling.
If the wait queue is full and the number of threads in the thread pool is less than maxPoolSize, new threads continue to be created to process the task.
If the queue is full and the number of threads has reached the limit, a Deny policy is used to handle it.
2. During the mission:
When the tasks in the queue have been executed, some threads start to idle, and non-core threads will destroy themselves within the keepAliveTime after idle.
Whether an idle core thread exits depends on another parameter of the thread pool, allowCoreThreadTimeOut. When configured to true, timeouts exit even core threads.
Lifetime of thread pool
Thread pools, like threads, also have their own life cycles, including RUNNING, SHUTDOWN, STOP, TIDYING and TERMINATED. Their transition relationships are shown below, and these transitions are irreversible.
1. RUNNING
This state is the working state of the thread pool, and it can accept new tasks and process accepted tasks. The initial state of the thread pool, which is processed after successful thread creation.
2. SHUTDOWN
Close state, the thread pool no longer accepts new tasks, but can continue to process tasks submitted to the thread pool. The shutdown() method is called to enter the thread state RUNNING.
3. STOP
Stop state, thread pool does not accept new tasks, does not process tasks in blocking queue, and interrupts threads executing tasks. Call shutdownNow() while the thread is in the RUNNING or SHUTDOWN state to enter that state.
4. TIDYING
All tasks are destroyed, workCount is 0, will automatically transition from RUNNING or STOP state to TIDYING state. The terminated() method is called during the conversion process. The terminated () method of the ThreadPoolExecutor class is empty. If you want to have something to handle when the thread pool becomes TIDYING, you can overload this method.
When the thread pool is in the SHUTDOWN state, the blocking queue is empty and the execution task is empty; when the thread pool is in the STOP state, the execution task is empty.
5. TERMINATED
End state, the final state of the thread pool in which there will be no more operations in the thread pool. The thread pool is in this state after executing the terminated() method.
JDK four thread pools
After understanding the basic principles of ThreaPoolExecutor, let's take a look at the four thread pool factory methods defined by JDK for developers in Executors. In fact, they call ThreaPoolExecutor internally, but use different parameters. Let's understand their characteristics.
newFixedThreadPool() method: This method returns a fixed number of threads in the thread pool. When submitting a task, if there are idle threads in the thread pool, it will be executed immediately. If there are no new tasks, it will be cached in a task queue. The code for creating the thread pool is as follows:
public static ExecutorService newFixedThreadPool(int nthread) { return new ThreadPoolExecutor(nthread, nthread, 0L, TimeUnit.MILLSECCONDS, new LikedBlockingQueue()) }
newSingleThreadExecutor() method: This method returns a thread pool with only one thread, and if extra tasks are submitted to the thread pool, they are submitted to the task queue. It creates thread pool code as follows:
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue())); }
newCachedThreadPool() method: This method returns a thread pool that can adjust the number of threads according to the actual situation. Its core thread number is 0, the total number of threads is Integer.MAX_VALUE, and the queue is SynchronousQueue, so that even if the thread is full, the task cannot be submitted to the queue.
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue()); }
newScheduled ThreadPool (): This method creates a fixed-length thread pool and executes tasks in a delayed or timed manner. Its queues use DelayedWorkQueue, so tasks must inherit the Delay interface.
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue(); } At this point, the study of "Java concurrency how to use thread pool" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!
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.