1

Hi everyone, my name is Mic.

The market environment this year is really difficult. Many people who have worked for one year, the difficulty of the interview is equivalent to a person with 4 years of experience.

image-20220518212100187

The more this is the case, the stronger we should be, in order to gain more opportunities in the face of adversity.

Today, a fan with one year of experience was asked about the "implementation principle of AQS" and came to me for help.

Check out the expert's answer to this question below.

Friends who like my works, remember to like, favorite and follow.

Expert:

AQS is a very core abstract class in the JUC package. It provides a queue synchronizer for multi-threaded access to shared resources.

In the JUC package, many components rely on AQS to synchronize and wake up threads, such as Lock, Semaphore, CountDownLatch, and so on.

AQS consists of two core parts:

  • A volatile modified state variable, as a race condition
  • FIFO thread waiting queue maintained by doubly linked list structure

Its specific working principle is that multiple threads implement race conditions by modifying this state shared variable.

Threads that fail to compete are added to the FIFO queue and blocked,

After the thread that has preempted the competitive resource is released, the subsequent threads wake up in an orderly manner according to the FIFO order.

image-20220519130818819

AQS provides two resource sharing methods,

One is the exclusive resource, only one thread can obtain the competitive resource at the same time. For example, ReentrantLock uses this method to implement exclusive locks

The other is to share resources. At the same time, multiple threads can obtain competitive resources at the same time. CountDownLatch or Semaphore is a way to use shared resources to wake up multiple threads at the same time.

Summarize

In actual development, if we need to implement some special mutually exclusive scenarios,

It is a bit troublesome to use ReentrantLock directly, then you can integrate AQS yourself and customize the implementation logic of multi-threaded competition.

This question mainly examines the understanding of the basics of Java.

file

Copyright notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated. Please indicate the source of Mic带你学架构 !
If this article is helpful to you, please help to follow and like, your persistence is the driving force for my continuous creation. Welcome to follow the WeChat public account of the same name to get more technical dry goods!

跟着Mic学架构
810 声望1.1k 粉丝

《Spring Cloud Alibaba 微服务原理与实战》、《Java并发编程深度理解及实战》作者。 咕泡教育联合创始人,12年开发架构经验,对分布式微服务、高并发领域有非常丰富的实战经验。