Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Happy birthday to our dear motherland, the motherland is becoming stronger day by day, we also want to come on oh, I love you, China!!

If faith had a color, I think it would be red.

Also wish XDM happy National Day everything wins meaning!!

This time use a living example to give you a quick look at how a thread pool works and what the seven parameters do.

Recently, I have been reviewing the interview questions to strengthen myself. Look at the interview questions after learning, can be very effective to know the deficiencies. It’s also preparation for the future.

Hello, I’m Ning Zaichun, a blogger.

Hope this article can let you gain, let us also work together!!

This paper mainly explains the seven parameters and working principle of the thread pool.

After reading this article, I can simply explain the working principle of thread pool and draw the schematic diagram in my own language.

1. Interview questions

There are a number of common thread pool questions in many Java interview articles and blogs.

👨💻

  1. Are threads used in your daily work? What are the advantages of thread pools?
  2. Describe how to use thread pools.
  3. Can you introduce the concepts and functions of the seven parameters of the thread pool? ,
  4. How does a thread pool work? Draw a diagram of how a thread pool works.
  5. Why not use the ThreadPoolExecutor implementation class instead of using Executors to create threads?
  6. How to configure a reasonable number of threads in the thread pool.

Problems, are step by step in-depth.

When we answer, the first thing to do is to make the interviewer as much as possible to their more confident in the past.


Seven parameters for the thread pool

The thread pool is created explicitly by using ThreadPoolExecutor instead of using the Executors tool class.

The reason:

[Mandatory] Thread resources must be provided through a thread pool. Explicit creation of threads in an application is not allowed. Note: The benefit of thread pooling is to reduce the time spent creating and destroying threads and the overhead of system resources, solving the problem of insufficient resources. If you don’t use thread pools, you can run out of memory or “overswitch” by creating a large number of similar threads.

【 Mandatory 】 Thread pools cannot be created by Executors. Use ThreadPoolExecutor to clear the running rules of the thread pool and avoid resource depletion. * If the thread pool object returns by Executors, it has the following disadvantages:

1) FixedThreadPool and SingleThreadPool: The allowed queue length is integer. MAX_VALUE, which may pile up a large number of requests, resulting in OOM.

2) CachedThreadPool: the number of threads allowed to create is integer. MAX_VALUE, which may create a large number of threads, resulting in OOM.

Java development manual from Ali

Let’s move on to today’s highlights:

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {}Copy the code

Parameter by parameter analysis:

  1. CorePoolSize – Number of core threads. The number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set

  2. MaximumPoolSize – The maximum number of concurrent threads in the pool, which must be greater than or equal to 1.

  3. KeepAliveTime – When the number of threads is greater than the number of cores, this is the maximum time that extra idle threads can wait for a new task before terminating.

    When the current thread pool exceeds corePoolSize, when the KeepAliveTime value is reached, the excess idle threads are destroyed until only corePoolSize remains.

  4. Unit – keepAliveTime Time unit of the keepAliveTime parameter

  5. WorkQueue – A queue used to save tasks before they are executed. This queue will only hold Runnable tasks submitted by the execute method.

  6. ThreadFactory – The factory that the execution program uses to create new threads, usually using the default.

  7. Handler – The handler used when execution is blocked because thread boundaries and queue capacity have been reached. Commonly known as the rejection strategy.

I will use a real-life example to explain how thread pools work to make sure everyone understands them.

How thread pools work

3.1 Schematic diagram

Let’s start with this chart:

1) When the execute() method is called to add a request task, the thread pool makes the following judgment:

  • If the number of running threads is less than corePoolSize, create a thread to run the task immediately.
  • If the number of running threads is greater than or equal to corePoolSize, the task is queued in a blocking queue;
  • If the queue is full and the number of running threads is less than maximumPoolSize, create a non-core thread to run the task immediately.
  • If the queue is full and the number of running threads is greater than or equal to maximumPoolSize, the thread pool initiates a saturation denial policy to execute.

2) When a thread completes a task, it takes the next task from the queue and executes it

3) When a thread has nothing to do for more than a certain amount of time, the thread decides:

  1. If the number of threads currently running is greater than corePoolSize, the thread is stopped.
  2. So after all the tasks in the thread pool are complete, it will eventually shrink to the size of corePoolSize.

4) Rejection policy, Jdk default rejection policy has the following four:

  1. AbortPolicy: Discarding the task, and throw refuse to enforce RejectedExecutionException exception information. Default reject policy for the thread pool. Exceptions must be handled properly. Otherwise, the current execution process will be interrupted and subsequent tasks will be affected.
  2. CallerRunsPolicy: When the reject policy is triggered, the calling thread is used to run the task directly as long as the thread pool is not closed. Generally, concurrency is small and does not require high performance. Failure is not allowed.
  3. DiscardPolicy: Directly discarded.
  4. DiscardOldestPolicyIf the thread pool is not closed,Discards the oldest task in the blocking queue and adds a new task to it

Above this content I read for the first time, also a little bit ignorant, when learning to understand, after a period of time to see again is a stranger.

This time, to make it more memorable, let me give you a particularly vivid example. From the Silicon Valley – Zhou Yang teacher

3.2 Life cases

I’m sure we’ve all been to the bank. Take the banks, for example. First look at the scene

Let me explain:

  1. A customer came to the bank and found that no one was dealing with business. He went directly to window no. 1 on duty to start dealing with business.

  2. Then another customer came, no one at window 2, so he went to window 2 on duty and began to handle business.

  3. Then came a third, a fourth, and a fifth customer. Now the first and second Windows on duty were doing business. They sat in the waiting area and began to wait.

  4. But then came a sixth, seventh, eighth customer. At this time, the waiting area was full, the lobby manager saw this situation, immediately told the president, need to increase the temporary window.

  5. Question? This time to add temporary window 3, 4, 5 will let who first to deal with business??

    Was it the sixth, seventh, and eighth customers, or the third, fourth, and fifth customers in the waiting area?

  6. I’ll handle the sixth, seventh, eighth customer that comes in.

  7. Reason: As I mentioned earlier, when the execute() method is called to add a request task, the thread pool makes the following decisions:

    If the queue is full and the number of running threads is less than maximumPoolSize, create a non-core thread to run the task immediately. Therefore, the sixth, seventh and eighth customers will be dealt with immediately.

  8. Continue, if there are more customers coming in to handle the business, the lobby manager sees this and triggers the rejection policy. (This is a strange situation, the manager dares to throw customers out.)

Let’s use code to simulate this scenario.

Code examples are used to further analyze the parameters

I’m going to set the data as it is,

CorePoolSize Indicates the number of core threads. MaximumPoolSize indicates the maximum number of core threads. KeepAliveTime indicates the wait time is 3 seconds

WorkQueue blocking queue for: 3, ThreadFactory thread to create a way to use the default: Executors. DefaultThreadFactory ()

RejectedExecutionHandler Reject the policy: all tests are performed.

    public static void main(String[] args) {

        BlockingDeque<Runnable> workQueue = new LinkedBlockingDeque<Runnable>(3);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2.5.3, TimeUnit.SECONDS,
                workQueue,
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i <8 ; i++) {
            final  int temp=i;
            executor.execute(()->{
                System.out.println(Thread.currentThread().getName()+"\t"+"Execution clause"+temp+"A mission!!"); }); }}Copy the code

The rejection policies set by the code: new ThreadPoolExecutor. AbortPolicy (), more than maximumPoolSize + workQueue the sum of the data. It just throws an exception and stops running.

When set to 8, it still works, so let’s try 9 tasks.

When we adjust upwards and the number of tasks exceeds the maximum, the rejection policy is triggered.

Change the strategy to new ThreadPoolExecutor. DiscardPolicy ()); I just dropped mission number eight.

Strategy is changed to: new ThreadPoolExecutor. CallerRunsPolicy (), when the trigger rejection policies, as long as, if not close the thread pool is used the calling thread run directly. Generally, concurrency is small and does not require high performance. Failure is not allowed.

DiscardOldestPolicy: Discarding the oldest task in the blocking workQueue and adding a new task to the queue as long as the thread pool is not closed

Five, talk to yourself

Hello, THIS is blogger Ning Zaichun: homepage

I hope you found this article useful!!

Wish us: by the time we meet on another day, we have achieved something.

No matter how far away or want to return home.

Station if it can record the story, he should have recorded a lot of joys and sorrows.