码迷,mamicode.com
首页 > 编程语言 > 详细

java学习之ReentrantLock

时间:2017-11-05 13:06:38      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:tran   dia   存在   flow   less   rac   ==   help   extend   

 本篇博文主要记录ReentranctLock内部实现原理。

 

ReentrantLock和Synchronized关键字相比,使用起来比较灵活。如何使用ReentranctLock就不多讲了,这里主要记录ReentrantLock的内部实现原理。

首先看下ReentrantLock的类继承结构, 如下图:

技术分享

 

ReentrantLock内部有三个内部类: Sync, FairSync, NonfairSync. 源码如下:

Sync:

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

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

  FairSync:

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

  NonfairSync:

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))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

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

  

FairSync实现了公平锁逻辑, NonfairSync实现的是非公平锁的逻辑。 下面看下最常使用的非公平锁的实现。

NonfairSync.lock()方法,首先基于CAS设置AQS中的state,如果返回true, 说明获取成功,此时将排他线程设置为当前线程。如果返回false, 说明获取失败,调用acquire(1)方法。acquire()方法在AQS中,代码如下:

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

  在acquire中首先再次获取锁, 如果获取失败, 则调用addWaiter()方法,将当前线程加入CHL队列。CHL队列结构如下:

 技术分享

加入队列后,然后调用方法acquireQueued(), 代码如下:

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

在acquireQueued()方法中,首先判断当前节点的前置节点是不是头结点,如果是头结点,则尝试获取锁,获取成功,则当前节点设置为头结点。否则判断是否应该讲当前节点对应的线程挂起, 如果前一个前一个节点的status是SIGNAL, 则说明需要将当前节点挂起。调用parkAndCheckInterrupt()方法挂起当前节点的线程。

 

上面是非公平锁的lock()逻辑,公平锁和非公平锁的,区别主要是公平锁在获取之前,首先需要判断是否存在前置节点,如果存在前置节点,则需要等待。我们看到FairSync中的tryAcquire()方法中,首先调用了hasQueuedPredecessors()方法,判断是否存在前置节点。

 

java学习之ReentrantLock

标签:tran   dia   存在   flow   less   rac   ==   help   extend   

原文地址:http://www.cnblogs.com/NewMan13/p/7787021.html

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