reentrantLock 介绍底层实现原理

10,206 阅读2分钟

我正在参加「掘金·启航计划」

reentrantLock 介绍底层实现原理

reentrantLock:公平锁和非公平锁.

 private Lock lock = new ReentrantLock();
 lock.lock(); //加锁
 lock.unlock(); //释放锁
1. lock.lock()源码分析
1.  调用内部抽象类 Sync的Lock()方法
    Sync 继承 AbstractQueuedSynchronizer(AQS)方法
    abstract static class Sync extends AbstractQueuedSynchronizer方法
    
2.  Sync的Lock()方法分别调用子类公平锁/非公平锁的类的Lock()方法
    static final class NonfairSync extends Sync
    //非公平锁
    final void lock() {
        if (compareAndSetState(0, 1))
            setExclusiveOwnerThread(Thread.currentThread());//修改成功 设置当前线程为独占锁
        else
            acquire(1); //获得锁
    }
    //公平所
    final void lock() {
        acquire(1);  //公平锁和非公平锁都是调用此方法 获得锁
    }
    
    //CAS原子操作 修改内存中的state字段的值
    protected final boolean compareAndSetState(int expect, int update) {
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }
    //如果没有修改成功/,没有获得锁 、  公平锁直接调用此方法
    public final void acquire(int arg) {
    //!tryAcquire(arg) 尝试获得锁 第一个线程,此方法肯定是false 
    //acquireQueued(addWaiter(Node.EXCLUSIVE), arg)  竞争锁 竞争不到的时候添加到队列里
    if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt(); // 只有在竞争锁的时候才会执行到这里
    }
    
    //非公平锁
    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
    final boolean nonfairTryAcquire(int acquires) {
        final Thread current = Thread.currentThread();//当前线程
        int c = getState(); // private volatile int state;
        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); //重新设置state的值
            return true;
        }
        return false; //都不满足:就是拥有锁的线程Thread1还在运行(还没有释放),Thread2 再次请求获得锁
    }
    
    //公平锁
    protected final boolean tryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) { //与非公平锁的区别就是  hasQueuedPredecessors()  此方法就是判断当前的线程在  Node节点/或者链表、(FIFO)同步队列 第一个节点。第一个线程进来,此方法返回肯定是false
            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;
    }
    //创建新的Node节点
    private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail; //第一个线程进来 是  null
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }
    //设置队列的head 和 tail 节点
    private Node enq(final Node node) {
        for (;;) {  //通过自旋方式
            Node t = tail;
            if (t == null) { // Must initialize
            //第一个线程进来  去内存中设置head 的值new Node() 变量tail = head;
                if (compareAndSetHead(new Node()))
                    tail = head; //因为用的是volatile修饰的  每次读取都是主内存中读取
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {  //CAS原子 设置尾节点Tail 为新建的node
                    t.next = node;
                    return t;
                }
            }
        }
    }
    
    //添加到队列
    final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                
                if (p == head && tryAcquire(arg)) {// 只有一个线程在队列里执行  并且抢到锁的情况下
                    setHead(node); //当前线程设置为head
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
    
    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;  //锁的等待状态
        if (ws == Node.SIGNAL)
            return true;
        if (ws > 0) {
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            areAndSetWaitStatus(pred, ws, Node.SIGNAL);  //设置为等待unPark
        }
        return false;
    }
    
    private final boolean parkAndCheckInterrupt() { //设置当线程阻塞 Park
        LockSupport.park(this);
        return Thread.interrupted();
    }
2. lock.unLock() 源码分析
1. 调用Sync的release方法
public void unlock() {
    sync.release(1);
}
public final boolean release(int arg) {
    if (tryRelease(arg)) {
        Node h = head; // unpark第一个(head)节点的线程
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);
        return true;
    }
    return false;
}
protected final boolean tryRelease(int releases) {
    int c = getState() - releases;
    if (Thread.currentThread() != getExclusiveOwnerThread()) //必须是加锁的线程才能释放锁
        throw new IllegalMonitorStateException();
    boolean free = false;
    if (c == 0) { //因为会有重入锁的概念 所以必须等到所有锁释放完才能通知其他线程
        free = true;
        setExclusiveOwnerThread(null);
    }
    setState(c);
    return free;
}

private void unparkSuccessor(Node node) {
    int ws = node.waitStatus;
    if (ws < 0)
        compareAndSetWaitStatus(node, ws, 0);//修改线程的等待状态为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 <= 0)
                s = t;
    }
    if (s != null)
        LockSupport.unpark(s.thread); //通知线程可以运行了
}