码迷,mamicode.com
首页 > 其他好文 > 详细

ReentrantLock--公平锁和非公平锁源码

时间:2021-04-07 11:23:49      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:初始   次数   success   ready   failure   should   tor   public   exce   

1:公平锁和非公平锁

1.1 流程图

技术图片

1.2 源码分析

? 锁使用

final Lock lock = new ReentrantLock();

        new Thread(()->{
            lock.lock();
            try {
                System.out.println("--------------------");
                Thread.sleep(10000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
1.2.1 CAS尝试获取锁:lock

? 公平锁:

final void lock() {
     acquire(1);
}

? 非公平锁:

final void lock() {
	//尝试获取锁,如果成功就可以获取到
    if (compareAndSetState(0, 1))
        setExclusiveOwnerThread(Thread.currentThread());
    else
    	//CAS失败,调用acquire进行获取
        acquire(1);
}

? 公平锁中没有直接进行CAS获取锁的流程,为了保证公平,而非公平会直接进行一次尝试。

? 非公平是作用于新入的节点,而已经调用过addWaiter方法的节点,则需要排队

? 两种锁,后面都会调用该方法,主要就是进行获取锁的尝试,如果获取到就退出,如果没有获取到,则需要将当前线程加入到队列中,知道获取到。

public final void acquire(int arg) {
    if (!tryAcquire(arg) &&     //进入1.2.2
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}
1.2.2 尝试获取锁tryAcquire(arg)

? 公平锁和非公平锁的区别是:hasQueuedPredecessors() ,该方法主要是判定是否有线程等待的时长大于当前判断线程。

? 公平锁:

protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    //锁的状态标记,0则是没有进行锁定,>0,则被锁,state值为锁定次数
    int c = getState();
    //0代表没有被锁定,开始尝试获取
    if (c == 0) {
        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;
}

? 非公平锁:

final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {
        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;
}

? 其中state是volatile修饰,保证可见,是线程安全的。

1.2.3 添加队列

如果上述获取锁失败,则需要将当前线程加入到队列之中。

? (1):如果队列不为空,则直接加入到队列末尾;

? (2):如果队列为空或者第一步添加失败,则重复进行添加;

? ReentranLock中多次运用该思想,先尝试进行,如果没有成功则循环重复进行。

private Node addWaiter(Node mode) {
	//创建一个Node,mode分为共享和排他
    Node node = new Node(Thread.currentThread(), mode);
    // Try the fast path of enq; backup to full enq on failure
    //对应于第一步,直接进行一次尝试添加
    Node pred = tail;
    if (pred != null) {
        node.prev = pred;
        if (compareAndSetTail(pred, node)) {
            pred.next = node;
            return node;
        }
    }
    //第一次尝试添加失败,则循环添加
    enq(node);
    return node;
}
private Node enq(final Node node) {
    for (;;) {
        Node t = tail;
        //队列为空,则构建一个空节点,并将自身添加到后面
        if (t == null) { // Must initialize
            if (compareAndSetHead(new Node()))
                tail = head;
        } else {
            node.prev = t;
            if (compareAndSetTail(t, node)) {
                t.next = node;
                return t;
            }
        }
    }
}
1.2.4 添加队列后处理
final boolean acquireQueued(final Node node, int arg) {
	//标识是否出现异常,出现异常会进入finally,取消获取
    boolean failed = true;
    try {
    	//标识线程在等待唤醒期间是否被打断
        boolean interrupted = false;
        //循环获取,直到获取到或者出现异常
        for (;;) {
        	//当前线程的pre节点
            final Node p = node.predecessor();
            //如果当前线程可以获取锁,并且获取成功
            if (p == head && tryAcquire(arg)) {
            	//当前节点设置为head
                setHead(node);
                p.next = null; // help GC
                failed = false;
                return interrupted;
            }
            //如果节点没有获取到锁,进行判断是否需要进行park
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

? 先进入:shouldParkAfterFailedAcquire(p, node)

  • CANCELLED:值为1,在同步队列中等待的线程等待超时或被中断,需要从同步队列中取消该Node的结点,其结点的waitStatus为CANCELLED,即结束状态,进入该状态后的结点将不会再变化。
  • SIGNAL:值为-1,被标识为该等待唤醒状态的后继结点,当其前继结点的线程释放了同步锁或被取消,将会通知该后继结点的线程执行。说白了,就是处于唤醒状态,只要前继结点释放锁,就会通知标识为SIGNAL状态的后继结点的线程执行。
  • CONDITION:值为-2,与Condition相关,该标识的结点处于等待队列中,结点的线程等待在Condition上,当其他线程调用了Condition的signal()方法后,CONDITION状态的结点将从等待队列转移到同步队列中,等待获取同步锁。
  • PROPAGATE:值为-3,与共享模式相关,在共享模式中,该状态标识结点的线程处于可运行状态。
  • 0状态:值为0,代表初始化狀態。
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
    int ws = pred.waitStatus;
    if (ws == Node.SIGNAL)
        /*
         * This node has already set status asking a release
         * to signal it, so it can safely park.
         */
        return true;
    if (ws > 0) {
        /*
         * Predecessor was cancelled. Skip over predecessors and
         * indicate retry.
         */
        do {
            node.prev = pred = pred.prev;
        } while (pred.waitStatus > 0);
        pred.next = node;
    } else {
        /*
         * waitStatus must be 0 or PROPAGATE.  Indicate that we
         * need a signal, but don‘t park yet.  Caller will need to
         * retry to make sure it cannot acquire before parking.
         */
        compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
    }
    return false;
}

上述如果返回的true,则标识当前线程进行park:

private final boolean parkAndCheckInterrupt() {
    LockSupport.park(this);
    return Thread.interrupted();
}
1.2.5 总结

? 以上为进行加锁的全流程,如果线程添加到队列中或者进入park,如果被唤醒或者开始获取到锁的,那么需要分析持有锁的线程在进行释放的时候做了哪些事情。

1.3 释放锁

public final boolean release(int arg) {
	//进行一次锁的释放
    if (tryRelease(arg)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
        	//唤醒下一个节点的线程
            unparkSuccessor(h);
        return true;
    }
    return false;
}
1.3.1 释放锁
protected final boolean tryRelease(int releases) {
	//退出一次,则将state减少一次
    int c = getState() - releases;
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException();
    boolean free = false;
    //c=0,标识持有锁的线程已经释放完,并把锁的当前线程置为null
    if (c == 0) {
        free = true;
        setExclusiveOwnerThread(null);
    }
    setState(c);
    return free;
}
1.3.2 唤醒
private void unparkSuccessor(Node node) {
    /*
     * If status is negative (i.e., possibly needing signal) try
     * to clear in anticipation of signalling.  It is OK if this
     * fails or if status is changed by waiting thread.
     */
    int ws = node.waitStatus;
    if (ws < 0)
        compareAndSetWaitStatus(node, ws, 0);

    /*
     * Thread to unpark is held in successor, which is normally
     * just the next node.  But if cancelled or apparently null,
     * traverse backwards from tail to find the actual
     * non-cancelled successor.
     */
    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 <= 0)
                s = t;
    }
    if (s != null)
        LockSupport.unpark(s.thread);
}

? 可以看出唤醒的是当前节点后面的节点。

ReentrantLock--公平锁和非公平锁源码

标签:初始   次数   success   ready   failure   should   tor   public   exce   

原文地址:https://www.cnblogs.com/mayang2465/p/14621269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!