ReentrantLock底层原理

一、步骤图

本文的整体用一张图来分析,如果符合你想要查看的内容再继续往下看吧

在这里插入图片描述


二、加锁阶段

lock()

new ReentrantLock()调用的是new NonfairSync();

线程1,CAS成功修改state = 1,setExclusiveOwnerThread = thread0

static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
            if (compareAndSetState(0, 1)) // CAS成功修改state = 1
                setExclusiveOwnerThread(Thread.currentThread()); // setExclusiveOwnerThread = thread0
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

acquire()

线程2,CAS失败,入等待队列,addWaiter(Node.EXCLUSIVE)

public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

tryAcquire()的实现类nonfairTryAcquire()

1)当前入队线程尝试插队(非公平锁),如果state = 0,则setExclusiveOwnerThread(current);

2)如果当前入队线程和当前独占线程相同(可重入锁),则state + 1。

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;
        }

addWaiter()

pred.next = node; 如果队列不为空,则自己在tail指向自己,然后将自己设置为tail

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;
        if (pred != null) {  //如果队列不为空
            node.prev = pred;  //node头连接tail
            if (compareAndSetTail(pred, node)) {  // node设置为tail
                pred.next = node; //tail尾连接node
                return node;
            }
        }
        enq(node);
        return node;
    }

enq()

因为一开始等待队列为空,进入enq()方法,开始CAS自旋创建队列,给Node创建一个head头结点,自身作为tail尾结点

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;
                }
            }
        }
    }

acquireQueued()

操作头结点,尝试tryAcquire()解锁

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)) { // 尝试tryAcquire()解锁
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

shouldParkAfterFailedAcquire()

自旋将头结点的waitStatus设置为-1,Node.SIGNAL的值为-1

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); // waitStatus设置为-1
        }
        return false;
    }

parkAndCheckInterrupt()

使用LockSupport.park()阻塞线程,还在selfInterrupt()中调用interrupt0()设置中断标志位。

private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this); // 阻塞线程
        return Thread.interrupted(); // 设置中断标志位
    }

三、解锁阶段

unlock()

new ReentrantLock().unlock()

public void unlock() {
        sync.release(1);
    }

release()

点进tryRelease()和unparkSuccessor()查看

public final boolean release(int arg) {
        if (tryRelease(arg)) { 
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

tryRelease()

因为在加锁的时候有说到可能会有重入锁的情况,所以tryRelease()会让state–,直到state=0,然后设置当前独占线程为null

protected final boolean tryRelease(int releases) {
            int c = getState() - releases; // state--
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);  // 设置当前独占线程为null
            }
            setState(c);
            return free;
        }

unparkSuccessor()

如果node的waitStatus为-1,CAS修改为0,而当等待队列node.next不为空,则LockSupport.unpark()唤醒下一个thread

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); // 修改waitStatus为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); // 唤醒next thread
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值