ReentrantLock 源码分析(一)

JDK 1.7.55

1, ReentrantLock 有一个内部类, 具体的操作是通过这个内部类来操作的。这个内部类就是同步器Sync, Sync是抽象类, 代码如下:

 

abstract static class Sync extends AbstractQueuedSynchronizer, 而AbstractQueuedSynchronizer 简称 AQS,继承关系如下:

 

public abstract class AbstractQueuedSynchronizer

    extends AbstractOwnableSynchronizer

    implements java.io.Serializable

 

下面我们看下 AbstractOwnableSynchronizer 的代码

 

public abstract class AbstractOwnableSynchronizer
    implements java.io.Serializable {

    /** Use serial ID even though all fields transient. */
    private static final long serialVersionUID = 3737899427754241961L;

    /**
     * Empty constructor for use by subclasses.
     */
    protected AbstractOwnableSynchronizer() { }

    /**
     * The current owner of exclusive mode synchronization.
     */
    private transient Thread exclusiveOwnerThread;

    /**
     * Sets the thread that currently owns exclusive access. A
     * <tt>null</tt> argument indicates that no thread owns access.
     * This method does not otherwise impose any synchronization or
     * <tt>volatile</tt> field accesses.
     */
    protected final void setExclusiveOwnerThread(Thread t) {
        exclusiveOwnerThread = t;
    }

    /**
     * Returns the thread last set by
     * <tt>setExclusiveOwnerThread</tt>, or <tt>null</tt> if never
     * set.  This method does not otherwise impose any synchronization
     * or <tt>volatile</tt> field accesses.
     * @return the owner thread
     */
    protected final Thread getExclusiveOwnerThread() {
        return exclusiveOwnerThread;
    }
}

 

 

上面我们看到的这个抽象的同步器只是有一个私有的属性 exclusiveOwnerThread。 这个地方有两个修饰符:

private  transient , private 表示除自己外,任何人不可以直接使用; transient 表示这个字段

不是串行化的一部分。 后台面的set和get方法,都是protected final 来修饰的, 这个表示子类

可以使用这个方法, 但是不能重载这个方法, 也就是不能修改这个方法。还有就是私有的构造

方法,表示这个抽象类是不能直接new来生成的。

 

 

2, AbstractQueuedSynchronizer 

这个类根据字面理解,也是一个抽象的同步器, 只不过是队列式的。在分析这个对象之前,需要分析它的一个内部类,就是 Node, 代码如下:

 

static final class Node {
        /** Marker to indicate a node is waiting in shared mode */
        static final Node SHARED = new Node();
        /** Marker to indicate a node is waiting in exclusive mode */
        static final Node EXCLUSIVE = null;

        /** waitStatus value to indicate thread has cancelled */
        static final int CANCELLED =  1;
        /** waitStatus value to indicate successor's thread needs unparking */
        static final int SIGNAL    = -1;
        /** waitStatus value to indicate thread is waiting on condition */
        static final int CONDITION = -2;
        /**
         * waitStatus value to indicate the next acquireShared should
         * unconditionally propagate
         */
        static final int PROPAGATE = -3;

        /**
         * Status field, taking on only the values:
         *   SIGNAL:     The successor of this node is (or will soon be)
         *               blocked (via park), so the current node must
         *               unpark its successor when it releases or
         *               cancels. To avoid races, acquire methods must
         *               first indicate they need a signal,
         *               then retry the atomic acquire, and then,
         *               on failure, block.
         *   CANCELLED:  This node is cancelled due to timeout or interrupt.
         *               Nodes never leave this state. In particular,
         *               a thread with cancelled node never again blocks.
         *   CONDITION:  This node is currently on a condition queue.
         *               It will not be used as a sync queue node
         *               until transferred, at which time the status
         *               will be set to 0. (Use of this value here has
         *               nothing to do with the other uses of the
         *               field, but simplifies mechanics.)
         *   PROPAGATE:  A releaseShared should be propagated to other
         *               nodes. This is set (for head node only) in
         *               doReleaseShared to ensure propagation
         *               continues, even if other operations have
         *               since intervened.
         *   0:          None of the above
         *
         * The values are arranged numerically to simplify use.
         * Non-negative values mean that a node doesn't need to
         * signal. So, most code doesn't need to check for particular
         * values, just for sign.
         *
         * The field is initialized to 0 for normal sync nodes, and
         * CONDITION for condition nodes.  It is modified using CAS
         * (or when possible, unconditional volatile writes).
         */
        volatile int waitStatus;

        /**
         * Link to predecessor node that current node/thread relies on
         * for checking waitStatus. Assigned during enqueing, and nulled
         * out (for sake of GC) only upon dequeuing.  Also, upon
         * cancellation of a predecessor, we short-circuit while
         * finding a non-cancelled one, which will always exist
         * because the head node is never cancelled: A node becomes
         * head only as a result of successful acquire. A
         * cancelled thread never succeeds in acquiring, and a thread only
         * cancels itself, not any other node.
         */
        volatile Node prev;

        /**
         * Link to the successor node that the current node/thread
         * unparks upon release. Assigned during enqueuing, adjusted
         * when bypassing cancelled predecessors, and nulled out (for
         * sake of GC) when dequeued.  The enq operation does not
         * assign next field of a predecessor until after attachment,
         * so seeing a null next field does not necessarily mean that
         * node is at end of queue. However, if a next field appears
         * to be null, we can scan prev's from the tail to
         * double-check.  The next field of cancelled nodes is set to
         * point to the node itself instead of null, to make life
         * easier for isOnSyncQueue.
         */
        volatile Node next;

        /**
         * The thread that enqueued this node.  Initialized on
         * construction and nulled out after use.
         */
        volatile Thread thread;

        /**
         * Link to next node waiting on condition, or the special
         * value SHARED.  Because condition queues are accessed only
         * when holding in exclusive mode, we just need a simple
         * linked queue to hold nodes while they are waiting on
         * conditions. They are then transferred to the queue to
         * re-acquire. And because conditions can only be exclusive,
         * we save a field by using special value to indicate shared
         * mode.
         */
        Node nextWaiter;

        /**
         * Returns true if node is waiting in shared mode
         */
        final boolean isShared() {
            return nextWaiter == SHARED;
        }

        /**
         * Returns previous node, or throws NullPointerException if null.
         * Use when predecessor cannot be null.  The null check could
         * be elided, but is present to help the VM.
         *
         * @return the predecessor of this node
         */
        final Node predecessor() throws NullPointerException {
            Node p = prev;
            if (p == null)
                throw new NullPointerException();
            else
                return p;
        }

        Node() {    // Used to establish initial head or SHARED marker
        }

        Node(Thread thread, Node mode) {     // Used by addWaiter
            this.nextWaiter = mode;
            this.thread = thread;
        }

        Node(Thread thread, int waitStatus) { // Used by Condition
            this.waitStatus = waitStatus;
            this.thread = thread;
        }
    }

 

这个Node其实就是一个自旋锁的队列,不是用这个来阻塞同步器,而是用它来保存节点种原来线程的一些信息。status这个字段来表示当前节点的线程是否需要阻塞,一个节点只有当它的前任被释放后才能唤醒,每个节点就想一个等待唤醒的监视器。STATUS 字段并不能保证能够得到锁, 队列里的第一个现成可以获得锁, 但是并不能保证能够得到锁,只是说它有竞争的权利。所以当前释放竞争锁的线程有可能灰重新等待。锁的结构如下:

            +------+  prev +-----+       +-----+

   head |          | <---- |         | <---- |       |  tail

            +------+       +-----+       +-----+

进队列,是需要添加到尾部,出队列,从头部开始。入队列需要原子性的操作,当然出队列也需要原子性的操作。

CLH队列需要有一个虚拟的头节点,我们这里并没有在构造的时候去创建,而是第一次使用的时候创建,这个能够在没有使用的时候可以提高效率。

prev指向的节点主要是用来处理取消操作的,如果节点被取消了,它的下个节点需要重新链到一个还没有取消的节点上面。

还用next的指向来实现阻塞的机制,每个节点对应的线程id都保存在节点内部,所以一个前任的节点表明下个节点需要唤醒,这个时候就需要用到这个next的指向来决定是那个线程需要唤醒。这个决定的过程,要避免和新增继任节点的竞争,怎样避免呢?是通过自动更新tail的指向,一直到这个节点的继任者为空。

 

 

这个时候的问题是: Node自己有对应的 prev 和 next  以及 waitStatus, 而且这三个属性都世 volatile 类型的,还有就是每个Node都有自己对应的线程,还有一个 nextWaiter。volatile 保证线程的写操作对其他线程是立即可见的, 但是不能保证操作的原子性, volatile只能保证他们写入的是同一块内存,但也有可能是写入脏数据synchronized 是用来修饰方法的,volatile 是用来修饰变量的。此处不理解的还有为什么有nextwaiter这个字段,还有 prev 和 next 两个属性。 根据里下面的代码推断Node应该是属于两种不同的模式,一种是等待的队列,一种条件队列,还有一种是默认的模式。具体代码参考上面的Node的三种构造方法。

 

对应的 AbstractQueuedSynchronizer 也有自己的 head 、tail 、state 属性,为什么它也有自己的头和伟,而且还是  transient volatile 类型的, 用transient 来修饰的变量,表明这个属性不会作为序列化的一部分。

 

 

 

 

 

 关于CLH自旋锁队列

 

http://blog.csdn.net/aesop_wubo/article/details/7533186

http://blog.csdn.net/aesop_wubo/article/details/7538934

http://christmaslin.iteye.com/blog/856395

http://blog.csdn.net/chen77716/article/details/6641477

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值