Get the App
SLTechnology News&Howtos  ›  Development  › 

How to understand unfair lock and fair lock

Shulou Source: shulou.com Published: 2022-06-03 01:31:35 09月10日 Update

This article mainly explains "how to understand unfair lock and fair lock". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. let's study and learn "how to understand unfair lock and fair lock".

An important difference between fair locks and unfair locks lies in the steps 2, 6 and 10 in the figure above, and the corresponding source codes are as follows:

/ / unfair lock final boolean nonfairTryAcquire (int acquires) {final Thread current = Thread.currentThread (); int c = getState (); if (c = = 0) {/ / see here if (compareAndSetState (0, acquires)) {setExclusiveOwnerThread (current); return true }} else if (current = = getExclusiveOwnerThread ()) {int nextc = c + acquires; if (nextc

< 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } //公平锁 protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { //hasQueuedPredecessors这个方法就是最大区别所在 if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } 分析以上代码,我们可以看到公平锁就是在获取锁之前会先判断等待队列是否为空或者自己是否位于队列头部,该条件通过才能继续获取锁。 在结合兔子喝水的图分析,非公平锁获取所得顺序基本决定在9、10、11这三个事件发生的先后顺序, 1、若在释放锁的时候总是没有新的兔子来打扰,则非公平锁等于公平锁; 2、若释放锁的时候,正好一个兔子来喝水,而此时位于队列头的兔子还没有被唤醒(因为线程上下文切换是需要不少开销的),此时后来的兔子则优先获得锁,成功打破公平,成为非公平锁; 其实对于非公平锁,只要线程进入了等待队列,队列里面依然是FIFO的原则,跟公平锁的顺序是一样的。因为公平锁与非公平锁的release()部分代码是共用AQS的代码。 private void unparkSuccessor(Node node) { int ws = node.waitStatus; if (ws < 0) compareAndSetWaitStatus(node, ws, 0); Node s = node.next; if (s == null || s.waitStatus >

0) {s = null; for (Node t = tail; t! = null & & t! = node; t = t.prev) if (t.waitStatus

Tags: Queue rabbit code that is thread sequence learning content time analysis maximum important success three upper and lower context picture above event sequence principle Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Redmi Shulou Information Docker Shulou Tech Info