Why do I need AQS? What is the role and importance of AQS?

The importance of AQS
Let's first introduce the importance of AQS (AbstractQueuedSynchronizer), to see which classes AQS is used in.
Insert picture description here
As shown in the figure, AQS is used in the Workers of ReentrantLock, ReentrantReadWriteLock, Semaphore, CountDownLatch, ThreadPoolExcutor (JDK 1.8), and AQS is the underlying principle of these classes.

Many of the above classes are commonly used classes, and most of them have been introduced in detail in the previous class. Therefore, many important tool classes in the JUC package are inseparable from the AQS framework, so the importance of AQS it goes without saying.

The idea of ​​learning AQS
Next, I want to introduce my understanding of the idea of ​​learning AQS. The internal structure of the AQS class is much more complicated than the general class . There are many details in it, which are not easy to fully grasp. Therefore, if we directly look at the source code when we come up, it is easy to stun ourselves, and it is easy to fall into the details. And go back.

In fact, most of our programmers are business developers, not JDK developers, so we don’t usually need to develop tools like ReentrantLock by ourselves, so generally speaking, we don’t directly use AQS for development. , Because the JDK has provided many encapsulated thread collaboration tool classes, like the previous ReentrantLock and Semaphore are provided to us by the JDK, and AQS is used internally, and these tool classes are basically enough to cover most of the business scenarios . This allows us to use these tools to develop smoothly even if we don't understand AQS.

The purpose of learning AQS is not to develop code, so why do we need to learn AQS? In my opinion, the main purpose of our study of AQS is to understand the principles behind it , learn design ideas, in order to improve technology and respond to interviews . So the main purpose is to interpret AQS from a macro perspective, such as knowing why AQS is needed and what is the role of AQS. After understanding the macro thinking, analyze its internal structure and learn more easily.

Locks and collaborations have something in common: valve function

Let the familiar class as the starting point to understand AQS, the previous ReentrantLock and Semaphore, are there any similarities between the two?

In fact, they can all be used as a valve. For example, if we set the number of licenses of Semaphore to 1, then because it has only one license, only one thread can pass through, and when the previous thread returns the license, it will allow other threads to continue to obtain the license. In fact, this is very similar to ReentrantLock. Only one thread can acquire the lock, and when this thread releases the lock, other threads are allowed to acquire the lock. Then if the thread finds that there is no additional license currently, or the lock is not currently available, the thread will be blocked, and will be awakened after the subsequent license or lock is released, so these links are relatively similar.

In addition to the ReentrantLock and Semaphore mentioned above, we will find that CountDownLatch, ReentrantReadWriteLock and other tool classes have similar functions to allow threads to "collaborate" . In fact, they are all implemented using AQS behind them.

Why do we need AQS

With the above foreshadowing, now think about it, why do we need AQS?

The reason is that the collaboration classes just mentioned above have a lot of similar work, so if you can extract the code that implements similar work and turn it into a new low-level tool class (or called a framework), you can Use this tool class directly to build the upper-level code, and this tool class is actually AQS.

With AQS, for thread collaboration tool classes such as ReentrantLock and Semaphore, they don't need to care about so many thread scheduling details, but only need to implement their respective design logic.

If there is no AQS

Then we try to think backwards, what would happen if there is no AQS?

If there is no AQS, then each thread collaboration tool class needs to implement at least the following, including:

  • Atomicity management of state
  • Thread blocking and unblocking
  • Queue management
    The status here has different meanings for different tool classes. For example, for ReentrantLock, it needs to maintain the number of times the lock is reentered , but the variable that saves the number of reentrants will be operated by multiple threads at the same time , It needs to be processed to ensure thread safety. Not only that, for those threads that have not grabbed the lock, they should be blocked, queued, and awakened at the right time. So these contents are actually more cumbersome and more repetitive, and these tasks are currently undertaken by AQS.

If there is no AQS, you need classes such as ReentrantLock to implement the relevant logic yourself, but it is quite difficult for each thread collaboration tool class to implement these contents correctly and efficiently. AQS can help us do all the "dirty work", so for classes such as ReentrantLock and Semaphore, they only need to pay attention to their own unique business logic. As the saying goes, "There is no time to be quiet, but someone is carrying the weight for you."

Analogy: HR and interviewer

If you see this, you still don't particularly understand the role of AQS, then please look at the following analogy. We compare AQS and thread collaboration tools to "personification" and compare them to HR and interviewers.

This simulates the scene of candidates participating in school recruitment interviews. For companies, interviews generally require the participation of interviewers and HR. There are usually two kinds of interviews, one is group face, the other is single face. Group face refers to an interview where multiple students participate together. For example, it is stipulated that 10 people are interviewed together. The group face rule is to gather 10 people first, and then Uniform interview.

Insert picture description here
And one-sided interviews are often streamlined, one-on-one. Suppose we have a total of 5 interviewers conducting one-sided interviews, that is, these 5 interviewers are interviewing a candidate at the same time. During the interview process, candidates will queue up. After the previous candidate has finished the interview, the latter candidate will follow , Find a free interviewer to start the interview, this is a one-sided scenario.
Insert picture description here
At first glance, the rules for group interviews and single-side interviews are very different: the former is for multiple interviews, while the latter is for one-by-one interviews. But in fact, the group side and the single side have many similarities ( or called processes or links), and these similarities are often taken care of by HR. For example, when an interviewer comes, HR needs to arrange for candidates to sign in, sit and wait, and queue, and then HR needs to call numbers in order to avoid conflicts between multiple candidates. At the same time, HR needs to ensure that all waiting students will eventually be called , The content of this series is in charge of HR, and the content is the same whether it is a single side or a group side. The work done by these HRs in the interview can actually be compared to the work done by AQS.

As for the specific interview rules, for example, is the group face rule 5 people or 10 people together? Is it single-sided or group? These are arranged by the interviewer. For the interviewer, he doesn't care about whether the candidate's number conflicts, how to wait, how to call the number, whether there is a place to rest, etc., because this is the scope of HR's responsibility.

The interviewer here corresponds to the use of AQS to implement specific collaborative logic tools, and HR stands for AQS . What I just said to let the candidate rest means to block the thread so as not to continue to consume the CPU; and the subsequent call for the candidate to go to the interview means to wake up the thread.

The process of the group face is similar to CountDownLatch. CountDownLatch will first set the initial value that needs to be counted down. Let's say it is 10. Every time a candidate comes, the count will be decremented. If all 10 people are there, the interview will start. Similarly, one-sided can be understood as a Semaphore semaphore. Assuming that there are 5 licenses, each thread obtains 1 license at a time, which is similar to having 5 interviewers in parallel interviews, and candidates need to obtain first before the interview Permit, return the permit after the interview.

For tools such as CountDownLatch and Semaphore, it has to determine its own "important" rules. Is it to gather 10 candidates for an interview, like a group? Or is it one out and one in, like one-sided? After the rules are determined, the remaining series of tasks such as greeting the interviewer (similar to scheduling threads) can be handed over to AQS. In this way, their respective responsibilities are very independent and distinct.

The role of AQS

Well, after having the above understanding, let's now summarize the role of AQS.

AQS is a framework for building thread collaboration tools such as locks and synchronizers . With AQS, many tools for thread collaboration can be easily written. With AQS, you can make higher-level tools. The development of AQS greatly reduces the workload, avoids re-creating wheels, and also avoids thread safety problems caused by improper handling by the upper layer, because AQS has done all these things. In short, with AQS, it is much easier for us to build thread collaboration tools.

to sum up

Learn the idea of ​​AQS, why you need AQS, and the role of AQS, using AQS can easily implement thread collaboration tools, and AQS is widely used in the JUC package.

Guess you like

Origin blog.csdn.net/Rinvay_Cui/article/details/114017660