In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how to analyze the thread pool. Many people may not know much about it. In order to let you know more, Xiaobian summarized the following contents for you. I hope you can gain something according to this article.
preface
Children's shoes that are usually exposed to too many threads should have more or less known about thread pools. There is also one in the previously published Alibaba Java Manual:
See the importance of thread pools.
Simply put, thread pools are used for several purposes:
Threads are scarce resources and cannot be created frequently.
Decoupling; threads are created completely separate from execution for ease of maintenance
They should be placed in a pool that can be reused for other tasks.
Thread pool principle
When it comes to thread pools, you will think of pooling technology, the core idea of which is to put precious resources into a pool; each time you use them, you get them from them, and then you put them back into the pool for others to use, which is a bit like eating a big pot of rice.
How is this implemented in Java?
After JDK 1.5, the API was introduced, and there are several common ways to create thread pools:
Executors.newCachedThreadPool(): Infinite thread pool.
Executors.newFixedThreadPool(nThreads): Creates a fixed-size thread pool.
Executors.newSingleThreadExecutor(): Creates a thread pool for a single thread.
In fact, if you look at the source code created in these three ways, you will find:
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue()); }
It is actually implemented using the ThreadPoolExecutor class.
So let's focus on how ThreadPoolExecutor is played.
The first is to create the API of the thread:
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, RejectedExecutionHandler handler)
The role of these core parameters:
corePoolSize is the base size of the thread pool.
maximumPoolSize is the maximum thread size of the thread pool.
keepAliveTime and unit are the time to live after the thread is idle.
workQueue A blocking queue for holding tasks.
handler Saturation policy when the queue and maximum thread pool are full.
Understand these parameters and then look at the actual application.
We usually use:
threadPool.execute(new Job());
This way to submit a task to the thread pool, so the core logic is the execute() function.
Before we analyze the details, we should first understand the states defined in the thread pool, which are closely related to the execution of threads:
RUNNING is naturally a running state, meaning that it can accept tasks in the task execution queue.
SHUTDOWN means that the shutdown() method is called and no new tasks are accepted, but the tasks in the queue have to be completed.
STOP means that the shutdownNow() method is called, no new tasks are accepted, all tasks in the blocking queue are discarded, and all executing tasks are interrupted.
TIDYING All tasks are completed and attempts to update to this state are made in calls to shutdown()/shutdownNow().
Terminated state, updated to this state when terminated() is executed.
Illustrated as:
Let's see how the execute() method works:
Gets the state of the current thread pool.
Create a new thread to run when the current thread count is less than coreSize.
If the current thread is running and the write to the blocking queue succeeds.
Double-check, get thread state again; if thread state changes (not running) remove task from blocking queue and try to determine if thread is all executed. And implement a denial policy.
If the current thread pool is empty, a new thread is created and executed.
If the determination in step 3 is non-running, try to create a new thread, and if it fails, execute the reject policy.
Here is a diagram from Concurrency to describe this process:
How to configure threads?
After the process chat, let's take a look at how several core parameters mentioned above should be configured?
One thing is for sure, thread pool is definitely not the bigger the better.
Usually we need to determine according to the nature of the task.
IO-intensive tasks: Since threads are not always running, you can configure as many threads as possible, such as the number of CPUs * 2.
CPU-intensive tasks (lots of complex calculations) should be allocated fewer threads, such as a comparable number of CPUs.
Of course, these are empirical values, and the best way is to test the most suitable configuration according to the actual situation.
Gracefully closing the thread pool
There are naturally running tasks and closing tasks. From the five states mentioned above, you can see how to close the thread pool.
Actually, there are only two ways:
shutdown()/shutdownNow()。
But there are important differences:
shutdown() stops accepting new tasks after execution, and completes the queue of tasks.
shutdownNow() also stops accepting new tasks, but interrupts all tasks and changes the thread pool state to stop.
Both methods interrupt threads, and the user can decide whether to respond to interrupts.
shutdownNow() is simpler and cruder, and you can choose different methods depending on the actual scene.
I usually close thread pools as follows:
long start = System.currentTimeMillis(); for (int i = 0; i
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.