Read the working principle of thread pool in one article

Preface

This article uses an example of a programmer's requirement to compare the working process of a thread pool. Unfold in the vernacular way of the story, explain the working principle of the thread pool to everyone, so that everyone can better understand the thread pool, thank you for reading~

  • What is a thread pool?
  • What is a core thread?
  • What is a blocking queue?
  • What is free time?
  • What is a saturation strategy?
  • What is a saturation strategy?
  • Thread pool working principle flowchart & source code overview

What is a thread pool?

"Little Ape" is diligent, hardworking, working day and night, and finally one day, he is promoted to the company's director and is responsible for the company's daily business.

One day, the boss found Xiao Yuan and said, "Our company has more and more employees. I want to build a **"employee management system"**. You can arrange it and it will be completed in one month. "The little monkey pats his chest, no problem!"

Because the company does not yet have a programmer, Xiao Yuan quickly opened **"Zubajie.com" and submitted the employee management system requirements. After waiting shortly, "Developer (name, thread A)"** took the order, negotiated the contract, and started development , System delivery...A series of processes and one month later, a comprehensive employee management system is finally completed...The boss greatly appreciates it~

Soon after, the boss said again, “More and more people in the company are late, let’s build a **“attendance system” !” Xiaoyuan received the task and immediately started to go to Zhubajie.com, asking for demand and finding someone to develop it. This time, "Thread B takes the order"**...

The deceased is like this. At the end of the month, the boss put forward the need to develop a salary system... The little ape heard that his scalp was numb, one day day, and repeatedly went online to find someone to develop it! "In order to save costs, why not hire a few programmers (threads a, b, c) and set up our own IT technology department! Let's call the IT department **"thread pool"**!" The boss listened. It's a hit!!!

The thread pool is a pool for managing threads. When there are tasks to be processed, new threads are not frequently created, but a thread is taken from the pool for processing. When the task is executed, the thread will not be destroyed, but is waiting for the next task.

What is a core thread?

After the establishment of the "Thread Pool" IT department, it hired several employees a, b, and c who had a formal contractual relationship with the company. The "Little Ape" managed a few of their regular employees as "core threads" . When the boss came up with a demand, Xiao Tian snail allocated the demand to the thread of **"No work on hand"**...

What is a blocking queue?

One morning, the boss was sleepy. After I came to the company, I mentioned the "four requirements" in one go . After a, b, and c got the task in order, I found that there was still one demand task left. How to arrange this? Did you go to the "Zhu Ba Jie Part-time Job Network" to find someone again? Established the "Thread Pool IT Department"**, and even went to find someone (thread work), people would laugh out loud!

The smart little ape thinks of a good way. We can create a DPMS demand pool, put the unallocated demand into the DPMS demand pool to be completed, and wait until who a, b, c finishes the work first, and then put this The task leads away. This DPMS demand pool, let's name it **"blocking queue" , and the English name "WorkQueue"**!

What is a non-core thread?

In another sunny afternoon, the boss drank a cup of coffee. He was fine in his free time, so he ran to the **"blocking queue" (DPMS demand pool) to have a look, and he was a fool at first sight! ! There are dozens of demands accumulated in the demand pool, and the schedule is full. The boss immediately called "Little Ape in the Office"** to discuss how to handle these demanding tasks.

"Or, how many more employees do we hire (how many more **"core threads" )? "No, no, the company's financial "overhead"** is a bit big! "

"Otherwise, do we ask the business to reduce the task requirements? ( "Request less" )" "Are you stupid, requesting less, aren't you going to cut your own money? You go home and think of a way first! ! "The boss magnified his voice~

The little ape went home and closed his eyes to let the gods. He went to bed early every day, not hearing things outside the window... Finally one day, in a dream fragrance, he thought of a good way. "Boss, we can go to another company ( "outsourcing company" ) to hire a few employees (assuming the names are d,e,f,g) for a period of time, and let them do **"DPMS demand pool (blocking queue)"* * The demand inside. Wait until the requirements are fulfilled, and then send them back. "The boss is happy when he hears it. This plan is good, and he feels happy: "Someone has done the work that needs it, and the company saves money. It has the best of both worlds" ~ these outsourced employees (d,e,f,g) , Let’s call it **"non-core thread"**.

What is free time?

Since d, e, f, g outsourced employees ( "non-core threads" ), the boss breathed a sigh of relief, so much work, finally someone did it.

But, another day, at the so-called off-duty time at 7 o'clock, the boss walked out of the office and found that the employees of the IT department of the "thread pool" were all gone in a hurry. I was furious: "How come these fans ran away after work hours, so their work is so unsaturated"**? He clicked into the DPMS demand pool and found out that the original demand had been fulfilled. . . There are also a bunch of outsourcing colleagues (non-core threads) who have to pay salaries. This wave of losses is huge~

The next day, Xiao Yuan was called into the boss's office by the ** "secret" , since the DPMS demand pool has no demand. Are we going to send an outsourced colleague (non-core thread) back? But generally, as soon as there is no demand, let them go back immediately ( "thread recycling"**), if the demand comes again all of a sudden, it will be a bit unholdable...

"Or else, when we wait for the pool to be empty, 15 or 10 days later, let the outsourcing colleagues ( "non-core threads" ) go back? "The 15 days or 10 days defined by this definition is **"thread idle survival time"**

What is a saturation strategy?

As Double 11 approached, not only the boss raised a lot of demands, but the new operating ladies also raised a lot of demands. New demands are coming like flowing water from the source~

First of all, the "thread pool" IT department a, b, c three formal employees (core threads) are busy processing the demand ( "request" ), then, the DPMS demand pool ( "blocking queue" ) is also full, and finally Well, even d, e, f, g outsourcing colleagues ( "non-core threads" ) are very busy.

At this time, the demand is still not finished, what should I do? How about going online on Double 11? The little ape has a sad face, from **"the tide rises and the sorrow reaches the tide"**...

There is no other way but to use the ** "saturation strategy" . For example, "discard demand tasks" ? "Throw the exception and tell the boss not to increase demand" ? "Discard the oldest demand task in the demand pool" ? Or "hand it over to the person who made the request"**?

Finally, the boss decided, "Refused to raise new requirements" , so the **"Thread Pool"** IT department is still running normally~

There are four main types of saturation strategy events in the line city pool

  • AbortPolicy (throw an exception, the default)
  • DiscardPolicy (newly submitted tasks are directly discarded)
  • DiscardOldestPolicy (discard the oldest task in the queue and continue to submit the current task to the thread pool)
  • CallerRunsPolicy (handed over to the thread where the thread pool is called for processing, that is, some tasks are rolled back to the caller)

Thread pool working principle flowchart & source code overview

The story is over, let’s review the workflow of the thread pool~

Friends who are interested, please check the source code too~

  if (command == null)
            throw new NullPointerException();
        int c = ctl.get();
        //判断当前活跃线程数是否小于corePoolSize
        if (workerCountOf(c) < corePoolSize) {
            //如果小于,则调用addWorker创建线程执行任务
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        //如果大于等于corePoolSize,则将任务添加到workQueue队列。
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        //如果放入workQueue队列失败,则创建非核心线程执行任务    
        else if (!addWorker(command, false))
            //(如果这时创建线程失败(当前线程数大于等于maximumPoolSize时))
            调用reject拒绝接受任务
            reject(command);

This article is transferred from https://xie.infoq.cn/article/ 29b6ca1c907a80b7d6149897b

[ Dissemination of knowledge, sharing of value ], thank you friends for your attention and support. I am [ Zhuge Xiaoyuan ], an Internet migrant worker struggling in hesitation.

Guess you like

Origin blog.csdn.net/wuxiaolongah/article/details/109520771