Brother Ao Bing, can you tell me about fair locks and unfair locks?

The more you know, the more you don’t know

Preface

Last time we mentioned optimistic locks and pessimistic locks, we know that there are many types of locks. Let’s briefly talk about fair locks and unfair locks, and their practices in our code.

text

Before starting the chat, let me briefly talk about the definitions of the two of them, to help you review or get to know them.

Fair lock: Multiple threads acquire locks in the order in which they apply for locks. The threads will directly enter the queue to queue up. They will always be the first in the queue to get the lock.

  • Advantages: All threads can get resources and will not starve to death in the queue.
  • Disadvantages: throughput will drop a lot, except for the first thread in the queue, other threads will be blocked, and the overhead of cpu waking up blocked threads will be very large.

Unfair lock: When multiple threads acquire a lock, they will directly try to acquire it. If they cannot acquire it, they will enter the waiting queue. If they can acquire the lock, they will directly acquire the lock.

  • Advantages: It can reduce the overhead of CPU waking up threads, the overall throughput efficiency will be higher, and the CPU does not have to wake up all threads, which will reduce the number of threads to be called.
  • Disadvantages: You may have also discovered that this may cause the thread in the middle of the queue to be unable to acquire the lock or acquire the lock for a long time, resulting in starvation.

I'll give him an easy-to-understand example. After thinking about it for several days, I finally found out how to give an example when I went to KFC to buy breakfast with Sanwai the day before yesterday.

It’s breakfast time. Ao Bing wants to go to KFC for breakfast, and found that there are a lot of people. Once he didn’t think much about it, he went to the end of the line obediently, so everyone felt fair. First come first served, so this is a fair lock Slightly.
Brother Ao Bing, can you tell me about fair locks and unfair locks?

The unfair lock is that Ao Bing went to buy breakfast and found that everyone was queuing, but Ao Bing was a bit scum, and he liked to jump in the line, so he went straight to the first one. The eggs and rice beans behind were all No, I jumped in and didn't dare to say anything, I could only endure it silently.
Brother Ao Bing, can you tell me about fair locks and unfair locks?

But occasionally, the eggs will rise, asking me to roll back to line up. I am also bullying and afraid of hardships. When I queued up in silence, I jumped in and failed.
Brother Ao Bing, can you tell me about fair locks and unfair locks?

After introducing a simple example, you may say, Zhabing, I also know this.

Should we return to the real implementation? In fact, there are related fair locks and unfair locks in the ReentrantLock that everyone often uses.

Do you still remember the Sync class I mentioned in the optimistic lock and pessimistic lock chapters? It is an internal class of ReentrantLock itself. It inherits AbstractQueuedSynchronizer. Most of the operations we operate on the lock are implemented by Sync itself.
Brother Ao Bing, can you tell me about fair locks and unfair locks?

Sync has two sub-categories: FairSync and NofairSync
Brother Ao Bing, can you tell me about fair locks and unfair locks?

The names of their subclasses can be seen by their names. How do fairness and unfairness manifest themselves at the code level?

Fair lock:
Brother Ao Bing, can you tell me about fair locks and unfair locks?

You can see that he added a judgement of hasQueuedPredecessors, so what is his judgement?
Brother Ao Bing, can you tell me about fair locks and unfair locks?

The general meaning of the code is to determine whether the current thread is at the top of the synchronization queue, if it is, it returns true, otherwise it returns false.

I always think it should be almost done by this, but I sat down and thought quietly and found that something was still missing.

I talked about ReentrantLock last time, but I just mentioned AQS and so on. When a thread comes in, what is the whole processing link like?

Is fair lock fair or unfair? Let us follow Bingbing into the inner world of ReentrantLock.

So much has been mentioned above, I think you should have some understanding, why is it unfair that a thread came into ReentrantLock? (The default is unfair lock)

Let me draw a picture first to help you understand the details:

ReentrantLock's Sync inherits AbstractQueuedSynchronizer, which is what we often call AQS
Brother Ao Bing, can you tell me about fair locks and unfair locks?

He is also the core of ReentrantLock's lock and release lock. I mentioned the general content in the previous issue. I won't repeat it too much. Let's take a look at the process of locking.

Thread A is ready to go in and acquire the lock. First, it judges the state state and finds that it is 0, so the CAS can succeed, and the thread currently holding the lock is modified as itself.
Brother Ao Bing, can you tell me about fair locks and unfair locks?

At this time, the B thread also came over, and it also went up to judge the state state first, and found that it was 1, then CAS failed, really unlucky, I can only wait for the queue obediently, wait for it to wake up, and go to sleep first. .
Brother Ao Bing, can you tell me about fair locks and unfair locks?

A has been holding it for a long time, and I am a little tired. I am ready to release the lock and give others a chance, so I changed the state, erased the trace of the thread holding the lock, and prepared to wake up B.
Brother Ao Bing, can you tell me about fair locks and unfair locks?

At this time, a boy C with a green hat came over and found out how the state is 0, decisively changed CAS to 1, and also modified the thread currently holding the lock for himself.

Thread B was woken up by A to get the lock, and found that the state was 1, and CAS failed, so I could only go back to the waiting queue. The route did not forget to scold A scumbag, how to deceive myself and deceive my feelings.
Brother Ao Bing, can you tell me about fair locks and unfair locks?

The above is an unfair lock thread. In this case, it is possible that a thread like B cannot obtain resources for a long time. The advantage is that some threads may reduce the waiting time and increase the utilization rate.

Now it is unfair by default. If you want to be fair, you have to pass the value true to the constructor.

ReentrantLock lock = new ReentrantLock(true);

Brother Ao Bing, can you tell me about fair locks and unfair locks?
After talking about unfairness, let me also talk about the fair process:

Line A now wants to obtain the lock. It first judges the state and finds that it is also 0. After looking at the queue, he is actually the first one and decisively modified the holding thread as himself.

Brother Ao Bing, can you tell me about fair locks and unfair locks?
Thread b is here, to judge the state, huh? Actually state=1, then cas failed, so I had to queue up obediently.
Brother Ao Bing, can you tell me about fair locks and unfair locks?
Unnamed file ( https://tva1.sinaimg.cn/large/00831rSTly1gcxaojuen2j30oa0jxgmh.jpg )
Untitled file ( https://tva1.sinaimg.cn/large/00831rSTly1gcxaojuen2j30oa0jxgmh.jpg )
thread A warm man is here, holding no How long will it take to release, change all the states, and wake up thread B. At this time, thread C has come in, but he first judged that the next state was 0, thinking there was a show, and then went to look at the queue and found that there was someone in front of it. , As a good citizen of the new era, decisively queued up.
Brother Ao Bing, can you tell me about fair locks and unfair locks?

Thread B gets the call of A, to judge the state, and finds that the value is 0, and it is also the first in the queue. That's very fragrant and you can get it.
Brother Ao Bing, can you tell me about fair locks and unfair locks?

to sum up:

In summary, I won’t say anything, but to get the source code of the lock judgment, the position pointed by the arrow, is it all reasonably explained by me now? The current thread, state, whether it is 0, whether it is the current thread, etc., all think under.
Brother Ao Bing, can you tell me about fair locks and unfair locks?

The ghost knows how much I did to draw the picture, is it too much to like it?
Brother Ao Bing, can you tell me about fair locks and unfair locks?

after class homework

Is fair lock really fair? So what level is not absolutely fair, what level can be considered fair?

I'm Ao Bing, a tool man who has survived on the Internet.

The best relationship is mutual achievement. Your "three consecutive" is the greatest motivation for Bingbing's creation. See you in the next issue!

Guess you like

Origin blog.51cto.com/14689292/2545802