This article has participated in the third “topic writing” track of the Denver Creators Training Camp. For details, check out: Digg Project | Creators Training Camp third is ongoing, “write” to make a personal impact.

Code shrimp is a sand carving and funny boy who likes listening to music, playing games and writing as well as most of his friends. The days are still very long, let’s refuel our efforts together 🌈

Welcome to follow my public account: JavaCodes, the name is with Java but the scope can be more than Java field oh 😁, will share blog posts or welfare for a long time, looking forward to your attention ❤

😉 offer yourself

Self-introduction, to everyone recommend their column 😁, welcome small partners to collect attention 😊

MybatisPlus column

App crawler Column

PC side crawler column

Big factory interview question column


✨ What is a thread pool?

Thread pooling: Creating a collection of threads during the initialization of a multithreaded application, and then re-using these threads as much as possible when new tasks are needed instead of creating a new thread.


🌈 This section describes thread pool types

🌈 Thread pool types – Executors


🌝 newFixedThreadPool ()

NewFixedThreadPool () : thread pool with a fixed number of threads

 public static ExecutorService newFixedThreadPool(int nThreads) {
     return new ThreadPoolExecutor(nThreads, nThreads,
                                   0L, TimeUnit.MILLISECONDS,
                                   new LinkedBlockingQueue<Runnable>());
 }
Copy the code
Thread pool features:
  • The number of core threads is the same size as the maximum number of threads
  • There is no such thing as non-idle time, i.e., keepAliveTime 0
  • The blocking queue is the unbounded queue LinkedBlockingQueue
disadvantages
  • If a task takes too long and a large number of tasks pile up in a blocking queue, or if a large number of tasks come in at any one time, the machine’s memory usage will spike, resulting in OOM
Usage scenarios

NewFixedThreadPool is suitable for processing CPU-intensive tasks, ensuring that the CPU is allocated as few threads as possible while being used by worker threads for a long period of time, that is, it is suitable for executing long tasks.


🌑 newCachedThreadPool ()

 public static ExecutorService newCachedThreadPool() {
     return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                   60L, TimeUnit.SECONDS,
                                   new SynchronousQueue<Runnable>());
 }
Copy the code
Thread pool features:
  • The number of core threads is 0
  • The maximum number of threads is integer.max_value
  • The blocking queue is SynchronousQueue
  • Non-core threads have an idle lifetime of 60 seconds
disadvantages
  • If tasks are submitted faster than threads can process them, new threads are constantly created, depleting CPU and memory resources in extreme cases
  • CachedThreadPoolThe number of threads allowed to be created is integer.max_value, which may create a large number of threads, resulting in OOM.
Usage scenarios

It is suitable for performing a large number of small, short-term tasks concurrently.

SynchronousQueue is unbounded and is an unbuffered wait queue


🌒 newSingleThreadExecutor ()

 public static ExecutorService newSingleThreadExecutor() {
     return new FinalizableDelegatedExecutorService
         (new ThreadPoolExecutor(1, 1,
                                 0L, TimeUnit.MILLISECONDS,
                                 new LinkedBlockingQueue<Runnable>()));
 }
Copy the code
Thread pool characteristics
  • The number of core threads is 1
  • The maximum number of threads is also 1
  • The blocking queue is LinkedBlockingQueue
  • KeepAliveTime of 0
disadvantages

LinkedBlockingQueue is an unbounded queue and may result in OOM

Usage scenarios

This mode applies to the scenario where tasks are executed sequentially, one by one.


🌓 newScheduledThreadPool ()

 public ScheduledThreadPoolExecutor(int corePoolSize) {
     super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
           new DelayedWorkQueue());
 }
Copy the code
Thread pool characteristics
  • The maximum number of threads is integer.max_value
  • The blocking queue is DelayedWorkQueue
  • KeepAliveTime of 0
  • ScheduleAtFixedRate () : Executes at a certain rate
  • ScheduleWithFixedDelay () : Executes after a certain delay
Usage scenarios

Scenarios where tasks are executed periodically and the number of threads needs to be limited


🌈 Description of thread pool types – Custom thread pool: ThreadPoolExecutor

Alibaba Java development manual is prohibitedExecutorsCreating a thread pool is recommendedThreadPoolExecutorCustom thread pool


ThreadPoolExecutor has seven parameters

CorePoolSize Number of core threads. If the number of core threads is not reached, a new thread will be created. When the number of core threads is reached, the task is queued

MaximumPoolSize Specifies the maximum number of threads. The value can be integer. MAX_VALUE, 2.1 billion. When the number of core threads is reached and the queue is full, additional threads are created to perform the task, up to the maximum number of threads

KeepAliveTime indicates the keepAliveTime. When the task is completed, additional threads are destroyed after a certain period of time. Idle wait time (this parameter does not apply to core threads by default. When allowCoreThreadTimeOut is manually set to true, core threads will not be destroyed until they have exceeded their lifetime)

TimeUnit Unit of idle waiting time

BlockingQueue: The task comes in. If the core thread count is full, the task is queued to wait.

The ThreadFactory thread creates the factory

RejectExecutionHandler Rejects the policy when the maximum number of threads is reached and the queue is full.

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}
Copy the code



🔥 How do I set the Java thread pool size?

The formula

  • CPU intensive task (N+1) : This type of task consumes CPU resources. The number of threads can be set to N (number of CPU cores) +1. One more thread is used to prevent occasional page miss interrupts or pauses caused by other reasons. Once the task is paused, the CPU is idle, and in this case the extra thread can take full advantage of the idle CPU time.
  • I/ O-intensive task (2N) : This is a task in which the system spends most of its time processing I/O interactions, and the thread does not occupy CPU for the time it is processing I/O, so the CPU can be handed over to another thread. Therefore, in the application of I/O intensive tasks, we can configure more threads, the specific calculation method is 2N.

Set the maximum number of threads

How to determine whether a CPU – intensive task or an IO – intensive task?

CPU intensive is simply a task that uses the computing power of the CPU such as sorting large amounts of data in memory.

As far as network reads are concerned, file reads are IO intensive. The characteristic of this type of task is that the CPU computation time is very small compared to the time spent waiting for THE I/O operation to complete. Most of the time is spent waiting for the I/O operation to complete.


❤ finally

I am aCode pipi shrimp, a prawns lover who loves to share knowledge, will update useful blog posts in the future, looking forward to your attention!!

Creation is not easy, if this blog is helpful to you, I hope you can == one key three even oh! Thank you for your support. See you next time