Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of handwritten AQS unfair Lock

Shulou Source: shulou.com Published: 2022-06-03 11:34:49 11月15日 Update

< 0) { throw new Error("超过最大锁计数"); } setState(nextState); return true; } return false; } /** * 添加等待队列 * * @param mode */ public Node addWaiter(Node mode) { Node node = new Node(mode, Thread.currentThread()); Node temp = tail; if (temp == null) { //入队 enQueue(node); return node; } else { //如果队列中不为空,就把当前节点添加到尾节点中 node.prev = temp; if (compareAndSetTail(temp, node)) { temp.next = node; return node; } } return node; } /** * 入队 * 把node节点添加到队列中, * 如果队列为null就初始化一个队列并且把node节点添加到尾节点中 * * @param node 返回当前节点 */ public Node enQueue(Node node) { while (true) { Node temp = tail; if (temp == null) { //创建一个头指针 compareAndSetHead(new Node()); //让尾指针也指向头指针(空节点) tail = head; } else { node.prev = temp; if (compareAndSetTail(temp, node)) { temp.next = node; return node; } } } } /** * @param node 当前正在侯队中得节点 * @param arg * @return */ protected boolean acquireQueued(Node node, int arg) { boolean failed = true; try { //是否被打断,默认false boolean interrupted = false; while (true) { final Node p = node.getPrev(); if (p == head && tryAcquire(arg)) { //如果是他的头节点是head,并且尝试抢占锁成功就出队,让当前线程运行 setHead(node); p.next = null;//利于gc回收 failed = false; return interrupted; } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) { //pre节点得waitStatus 设置成-1,并且让当前线程阻塞,打断当前线程 interrupted = true; } } } finally { if (failed) cancelAcquire(node); } } protected final void cancelAcquire(Node node) { if (node == null) return; node.thread = null; Node pre = node.prev; while (pre.waitStatus >

0) {node.prev = pre = pre.prev;} Node predNext = pre.next; node.waitStatus = Node.cancelled; if (node = = tail & & compareAndSetTail (node, pre)) {compareAndSetNext (pre, predNext, null);} else {/ / If successor needs signal, try to set pred's next-link / / so it will get one. Otherwise wake it up to propagate. Int ws; if (pre! = head & & (ws = pre.waitStatus) = = Node.signal | | (ws 0) {do {pre = pre.prev; node.prev = pre;} while (pre.waitStatus > 0); pre.next = node } else {/ / set to-1 boolean flag = compareAndSetWaitStatus (pre, ws, Node.signal); / / System.out.println ("whether the setting to-1 is successful:" + flag);} return false } / * block the current thread and return the current thread's interrupted status * * @ return true: thread interrupted successfully * / protected final boolean parkAndCheckInterrupt () {/ / interrupt the thread to block LockSupport.park (this); return Thread.interrupted ();} public Node getHead () {return head } public void setHead (Node head) {this.head = head;}}

3. Realized by unfairness

Package com.shi.flink.shilock;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;/** * Custom unfair Lock * @ author shiye * @ create 2021-03-30 11:02 * / public class ShiNonfairLock extends ShiAQS implements Lock, java.io.Serializable {private static final long serialVersionUID = 7373984872572414699L @ Override public void lock () {if (compareAndSetState (0,1)) {/ / if you grab the lock, set the current thread to setExclusiveOwnerThread (Thread.currentThread ());} else {/ / otherwise queue acquire (1) } @ Override public void lockInterruptibly () throws InterruptedException {} @ Override public boolean tryLock () {return false;} @ Override public boolean tryLock (long time, TimeUnit unit) throws InterruptedException {return false;} @ Override public void unlock () {try {super.release (1);} catch (Exception e) {e.printStackTrace () } @ Override public Condition newCondition () {return null;} / * interrupt a thread (written by yourself, including bug) * @ param thread * @ return * / public boolean interruptThread (Thread thread) throws Exception {return super.interruptThread (thread);}}

4. test

Package com.shi.flink.shilock;import java.util.concurrent.TimeUnit;/** * @ author shiye * @ create 2021-03-31 17:09 * / public class MyLockTest {public static void main (String [] args) throws Exception {ShiNonfairLock lock = new ShiNonfairLock (); new Thread (()-> {try {System.out.println ("A thread enters. Lock process "); lock.lock (); System.out.println (" A has preempted the lock. Run after 10 seconds of hibernation. "); TimeUnit.SECONDS.sleep (10);} catch (Exception e) {e.printStackTrace ();} finally {System.out.println (" A thread finishes running and starts unlocking.... "); lock.unlock () }, "A"). Start (); TimeUnit.SECONDS.sleep (1); Thread B = new Thread (()-> {try {System.out.println ("B thread enters. Lock process "); lock.lock (); System.out.println (" B has preempted the lock. Run after 10 seconds of hibernation. "); TimeUnit.SECONDS.sleep (10);} catch (Exception e) {e.printStackTrace ();} finally {System.out.println (" B thread finishes running and starts unlocking.... "); lock.unlock () }, "B"); B.start (); TimeUnit.SECONDS.sleep (1); new Thread (()-> {try {System.out.println ("C thread enters. Lock process "); lock.lock (); System.out.println (" C has preempted the lock. Run after 10 seconds of hibernation. "); TimeUnit.SECONDS.sleep (10);} catch (Exception e) {e.printStackTrace ();} finally {System.out.println (" C thread finishes running and starts unlocking.... "); lock.unlock () }, "C"). Start (); TimeUnit.SECONDS.sleep (1); new Thread (()-> {try {System.out.println ("D thread enters. Lock process "); lock.lock (); System.out.println (" D has preempted the lock. Run after 10 seconds of hibernation. "); TimeUnit.SECONDS.sleep (10);} catch (Exception e) {e.printStackTrace ();} finally {System.out.println (" D thread finishes running, start unlocking.... "); lock.unlock () }, "D"). Start (); / / TimeUnit.SECONDS.sleep (1); / / System.out.println ("force" + B.getName () + "thread interrupt."); / / lock.interruptThread (B);}} after reading the above, have you mastered the method of example analysis of handwritten AQS unfair locks? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Thread state node run pointer attempt success hibernation indication procedure method in progress example analysis content more tag idle problem blocking Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi MySQL Shulou Tech Info NVidia MariaDB