Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

java锁ReentrantLock源码分析 #23

Open
diaosichengxuyuan opened this issue Feb 17, 2019 · 0 comments
Open

java锁ReentrantLock源码分析 #23

diaosichengxuyuan opened this issue Feb 17, 2019 · 0 comments

Comments

@diaosichengxuyuan
Copy link
Owner

diaosichengxuyuan commented Feb 17, 2019

ReentrantLock是可重入的排它锁,支持公平和非公平模式,通过AbstractQueuedSynchronizer实现

lock()和unlock()

   public void lock() {
        sync.lock();
    }

    public void unlock() {
        sync.release(1);
    }
abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = -5179523762034025860L;

        /**
         * Performs {@link Lock#lock}. The main reason for subclassing
         * is to allow fast path for nonfair version.
         */
        abstract void lock();

        /**
         * Performs non-fair tryLock.  tryAcquire is implemented in
         * subclasses, but both need nonfair try for trylock method.
         */
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            //获取状态
            int c = getState();
            //如果获取状态成功
            if (c == 0) {
                //通过CAS将状态从0改成1
                if (compareAndSetState(0, acquires)) {
                    //设置当前的独占线程
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            //如果当前状态不是0,但是当前独占线程是当前线程,表示是当前线程进行了重入
            else if (current == getExclusiveOwnerThread()) {
                //继续增加状态
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                //设置状态,不用CAS方式,因为只有当前线程获取了锁
                setState(nextc);
                return true;
            }
            return false;
        }

        protected final boolean tryRelease(int releases) {
            //状态每次减1
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            //如果状态已经释放完成
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
           //设置状态,c可能等于0也可能不等于0,如果等于0,则返回true;如果不等于0,则返回false
            setState(c);
            return free;
        }

        final ConditionObject newCondition() {
            return new ConditionObject();
        }
}
    //非公平模式
    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() {
            //如果通过CAS获取状态0成功,将状态修改为1
            if (compareAndSetState(0, 1))
                //设置当前的独占线程为当前线程
                setExclusiveOwnerThread(Thread.currentThread());
            //如果获取状态不成功
            else
                //调用AbstractQueuedSynchronizer中的acquire
                acquire(1);
        }
        
        //尝试获取状态1
        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }
//公平模式
static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

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

        /**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        //公平模式获取锁的线程是在同步队列中排队的线程,谁先排队谁先获得,与非公平模式仅有下面一点 
        //不同
        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;
        }
    }
public abstract class AbstractQueuedSynchronizer
    extends AbstractOwnableSynchronizer
    implements java.io.Serializable {
       
        public final void acquire(int arg) {
        //先判断tryAcquire(1)是否成功,如果成功,直接返回,表示获取到了锁
        //如果获取状态失败,addWaiter(Node.EXCLUSIVE),将当前线程组装成Node添加到同步队列中
        //acquireQueued是将当前线程进行自循环
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
         }
        
        //添加到同步队列
        private Node addWaiter(Node mode) {
        //将当前线程组装成Node
        Node node = new Node(Thread.currentThread(), mode);
        Node pred = tail;
        //如果同步队列不为空
        if (pred != null) {
            node.prev = pred;
            //通过CAS将node添加到同步队列的队尾
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        //如果队列为空或者CAS添加到队尾时失败
        enq(node);
        return node;
    }
     
    //死循环方式将node添加到同步队列队尾
    private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { 
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, 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();
                //head是已经获取锁的线程,当前线程需要判断自己的前驱是否是head,如果是head,则尝试
                //获取状态1,如果获取状态成功,将自己设置成head,断开与前驱的关联
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                //如果当前线程前驱不是head或者获取状态1失败,LockSupport.park(this),阻塞当前线程
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

    //释放状态
    public final boolean release(int arg) {
        //如果尝试释放状态成功
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                //唤醒同步队列中的下个线程
                unparkSuccessor(h);
            return true;
        }
        return false;
    }
}

作者原创,转载请注明出处,违法必究!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant