In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what are the main parameters of the thread pool". In the daily operation, I believe that many people have doubts about the main parameters of the thread pool. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what are the main parameters of the thread pool?" Next, please follow the editor to study!
(1) what is a thread pool
Thread is the smallest unit that the operating system can schedule operations. It is included in the process, is the actual operating unit of the process, our programs are ultimately run by threads. In Java, the act of creating and destroying threads is very resource-consuming, so the so-called "pooled resource" technology has emerged.
Thread pool is an application of pooling resource technology. The so-called thread pool, as its name implies, means that several executable threads are created in advance and put into a container (thread pool) according to a certain stipulation. When needed, they are taken from the thread pool and put back instead of being destroyed after use, thus reducing the number of thread creation and destruction and achieving the goal of saving resources.
(2) Why should thread pool 2.1 be used to reduce resource consumption
As mentioned earlier, the emergence of thread pools reduces the number of thread creation and destruction, and each thread can be reused to perform multiple tasks.
2.2 improve the response speed of the system
Whenever a task arrives, directly reuse the threads in the thread pool without waiting for the creation of new threads. This action can improve the response speed.
2.3 prevent too many threads from damaging the system
The number of worker threads in the thread pool can be adjusted according to the bearing capacity of the system to prevent the server from slowing down or crashing because of too many threads. Java A thread takes up 1m of space by default, so you can imagine that if you create too many threads manually, it is very likely to cause a memory overflow.
(3) main parameters of thread pool
We can use the Executors class to create some commonly used thread pools, but Ali forbids the creation of thread pools directly through the Executors class. The specific reasons will be discussed later.
Before we look at the thread pools provided by the Executors class, let's first take a look at the main parameters of ThreadPoolExecutor. ThreadPoolExecutor is the class that creates the thread pool. Let's take a look at the constructor with the most parameters:
Public ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory RejectedExecutionHandler handler) name type meaning corePoolSizeint core thread pool size maximumPoolSizeint maximum thread pool size keepAliveTimeless thread maximum idle time unitTimeUnit time unit workQueueBlockQueueThreadFactoryThreadFactoryThreadFactoryThreadFactoryThreadFactoryThreadFactoryThreadFactoryThreadFactoryThreadFactory rejection policy 3.1 corePoolSize
When submitting a task to the thread pool, if the number of threads created in the thread pool is less than corePoolSIze, even if there are idle threads, a new thread is created to execute the task until the number of threads created is greater than or equal to corePoolSIze.
3.2 maximumPoolSize
The maximum number of threads allowed in the thread pool, when the queue is full and the number of threads already created is less than maximumPoolSize, a new thread is created to execute the task.
3.3 keepAliveTime
When the number of threads in a thread is greater than corePoolSIze, if the idle time of the thread is greater than keepAliveTime, the thread will be destroyed.
3.4 unit
The time unit of the keepAliveTime
3.5 workQueue
Used to save queues waiting for tasks to be executed
3.6 threadFactory
Used to create a new thread. The thread created by threadFactory also uses the new Thread () method, and the thread name created by threadFactory has a unified style: pool-m-thread-n
3.7 handler
Reject policy, which is executed when a new thread is added when the thread pool and queue are full. Here are four thread pool rejection strategies:
AbortPolicy: interrupting the task and throwing an exception
DiscardPolicy: middle task without throwing an exception
DiscardOldestPolicy: discard the oldest task in the queue and then try to submit a new task
CallerRunsPolicy: the task is handled by the calling thread
(4) execution process of thread pool
When we understand the seven parameters of ThreadPoolExecutor, we can quickly understand the flow of the thread pool:
After submitting the task, first determine whether the current number of threads exceeds the number of core threads, if not, create a new thread to execute the task, otherwise determine whether the work queue is full, and add the task to the queue if it is not full, otherwise determine whether the number of threads exceeds the maximum number of threads, if not, create a thread to execute the task, otherwise execute the rejection policy.
(5) Thread pool provided by Executors
Executors provides many kinds of thread pools for users to use, although many companies prohibit the use of executors to create thread pools, but for those who are just beginning to release the thread pool, the thread pool provided by the Executors class can take you into the multithreaded world.
5.1 newSingleThreadExecutorExecutorService executorService = Executors.newSingleThreadExecutor ()
Listen to the name to know that this is a single-threaded thread pool, in which only one thread is working, which is equivalent to a single thread executing all tasks. This thread can ensure that all tasks are executed in the order in which they are submitted. As can be seen from the constructor, both corePoolSize and maximumPoolSize are 1.
Public static ExecutorService newSingleThreadExecutor () {return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor (1,1,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue ();} 5.2newFixedThreadPoolExecutorService executorService = Executors.newFixedThreadPool (2)
A fixed-length thread pool whose length is passed in by variable at creation time. Here is the construction method of newFixedThreadPool. CorePoolSize and maximumPoolSize are both passed parameter values.
Public static ExecutorService newFixedThreadPool (int nThreads) {return new ThreadPoolExecutor (nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue ());} 5.3 newCachedThreadPoolExecutorService executorService = Executors.newCachedThreadPool ()
Cacheable thread pool, which sets keepAliveTime to 60 seconds and has little control over the maximum number of threads.
Public static ExecutorService newCachedThreadPool () {return new ThreadPoolExecutor (0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue ());}
Observe the construction method, corePoolSize = 0 maximumPoolSize = Integer.MAX_VALUE, that is, there is almost no limit to the number of threads. Set the keepAliveTime to 60 seconds, and the thread ends automatically after it is idle for 60 seconds. Because the thread pool is created with no limit and there is no queue waiting, the SynchronousQueue synchronization queue is used.
5.4 newScheduledThreadPool
Create a timed thread pool. This thread pool supports the need for scheduled and periodic execution of tasks. Here is the use of newScheduledThreadPool:
Thread thread1=new Thread (new Runnable () {@ Override public void run () {System.out.println (Thread.currentThread (). GetName () + "thread1");}); Thread thread2=new Thread (new Runnable () {@ Override public void run () {System.out.println (Thread.currentThread (). GetName () + "thread2");}})) Thread thread3=new Thread (new Runnable () {@ Override public void run () {System.out.println (Thread.currentThread (). GetName () + "thread3");}}); ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor (); / / execute thread1scheduledExecutorService.schedule (thread1,1000,TimeUnit.MILLISECONDS) after 1000ms; / / execute thread2 every other 1000ms after 1000ms, and delay the execution of scheduledExecutorService.scheduleAtFixedRate (thread2,1000,1000,TimeUnit.MILLISECONDS) if the task execution time is longer than the interval / / similar to the second method, but the start time of the next task is: the last task end time (not the start time) + delay time scheduledExecutorService.scheduleWithFixedDelay (thread3,1000,1000,TimeUnit.MILLISECONDS); (6) Why Alibaba forbids programmers to create thread pools with Exectors
If your idea is equipped with the Alibaba Java Codeing Guidelines plug-in (recommended to help make your code more standardized), you will see a prompt when you write Exectors to create a thread pool:
And Ali defines this usage as Blocker, which is not allowed, but allows people to create thread pools in the way of ThreadPoolExecutor. The reason is that through ThreadPoolExecutor, this processing method makes the writer more clear about the running rules of the thread pool and avoids the risk of resource exhaustion.
The disadvantages of the thread pool object returned by Executors are as follows:
1) FixedThreadPool and SingleThreadPool:
The request queue length allowed by is Integer.MAX_VALUE, which may pile up a large number of requests, resulting in OOM. 2) CachedThreadPool:
The number of creation threads allowed by is Integer.MAX_VALUE, which may create a large number of threads, resulting in OOM. here is a simple example of ThreadPoolExecutor creating a thread pool
Int corePoolSize=5;int maximumPoolSize=10;long keepAliveTime=30;BlockingQueue blockingQueue=new ArrayBlockingQueue (2); RejectedExecutionHandler handler=new ThreadPoolExecutor.AbortPolicy (); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor (corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, blockingQueue, handler); threadPoolExecutor.execute (thread1); (VII) use thread pools in SpringBoot projects
SpringBoot encapsulates the thread pool again. In SpringBoot, the thread pool can be created through the ThreadPoolTaskExecutor class. You need to note the difference between the two. ThreadPoolExecutor is the class under the JUC package, and ThreadPoolTaskExecutor is the class under the springframework package. But the principle is the same.
7.1 Project Building
First set up a SpringBoot project, only need to introduce web dependency
Org.springframework.boot spring-boot-starter-web7.2 profile configuration
The parameters of the thread pool are written into the configuration file as much as possible so that they can be modified as needed and configured in the application.properties file:
MyExecutor.corePoolSize=5myExecutor.maxPoolSize=10myExecutor.keepAliveSeconds=30myExecutor.allowCoreThreadTimeOut=falsemyExecutor.queueCapacity=20myExecutor.threadNamePrefix=myExecutor-7.3 writes its own thread pool
Create a new package called config, create a new class ExecutorConfig, first get the value of the parameter from the configuration file, and then create your own thread pool with ThreadPoolTaskExecutor and inject it into the Bean container.
@ Configuration@EnableAsyncpublic class ExecutorConfig {@ Value ("${myExecutor.corePoolSize}") private int corePoolSize; @ Value ("${myExecutor.maxPoolSize}") private int maxPoolSize; @ Value ("${myExecutor.keepAliveSeconds}") private int keepAliveSeconds; @ Value ("${myExecutor.allowCoreThreadTimeOut}") private boolean allowCoreThreadTimeOut; @ Value ("${myExecutor.queueCapacity}") private int queueCapacity; @ Value ("${myExecutor.threadNamePrefix}") private String threadNamePrefix @ Bean ("myExecutor") public Executor myExecutor () {ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor (); / / number of core threads executor.setCorePoolSize (corePoolSize); / / maximum number of threads executor.setMaxPoolSize (maxPoolSize); / / thread idle time executor.setKeepAliveSeconds (keepAliveSeconds); / / whether to keep the number of core threads executor.setAllowCoreThreadTimeOut (allowCoreThreadTimeOut) / / queue length executor.setQueueCapacity (queueCapacity); / / reject policy executor.setRejectedExecutionHandler (new ThreadPoolExecutor.AbortPolicy ()); / / set thread name prefix executor.setThreadNamePrefix (threadNamePrefix); executor.initialize (); return executor;}}
It should be noted that there is a method setAllowCoreThreadTimeOut. When the parameter is true, all threads will be destroyed after timeout. If it is false, only the number of core threads will be exceeded and the timeout will be destroyed.
7.4 write service and use the
First, write a service interface:
Public interface DoSomeThing {/ * execute time-consuming tasks asynchronously through thread pool * / public void doSomeThing ();}
Then write the implementation class:
@ Servicepublic class DoSomeThingImpl implements DoSomeThing {@ Override @ Async ("myExecutor") public void doSomeThing () {System.out.println (Thread.currentThread (). GetName () + "- in"); try {Thread.sleep (5000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println (Thread.currentThread (). GetName () + "- out") }}
With the addition of the annotation @ Async ("myExecutor"), this method is executed asynchronously by the myExecutor thread pool.
7.5 write a controller
Create a new IndexController and execute the doSomeThing () method once per request.
@ RestControllerpublic class IndexController {@ Autowired private DoSomeThing doSomeThing; @ RequestMapping (value = "/ index", method = RequestMethod.GET) public String index () {doSomeThing.doSomeThing (); return "success";}} 7.6Test
If the http://localhost:8080/index is accessed ten times, the number of core threads set is 5 and the queue capacity is 30, so a maximum of 5 thread resources will be used. The result is as follows:
At this point, the study of "what are the main parameters of the thread pool" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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: 277
*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.