`

ReentrantLock 源码分析(一)

    博客分类:
  • java
 
阅读更多

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

 

 

 

分享到:
评论

相关推荐

    ReentrantLock源码分析

    近日,阅读jdk并发包源码分析整理笔记。

    7、深入理解AQS独占锁之ReentrantLock源码分析(1).pdf

    7、深入理解 AQS 独占锁之 Reentrantlock 源码分析 (1).pdf 8、读写锁ReentrantReadWriteLock&StampLock详解.pdf 9、并发容器 (Map、List、Set) 实战及其原理.pdf 10、阻塞队列BlockingQueue 实战及其原理分析.pdf

    Java并发系列之ReentrantLock源码分析

    主要为大家详细介绍了Java并发系列之ReentrantLock源码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

    带你看看Java的锁(一)-ReentrantLock

    带你看看Javad的锁-ReentrantLock前言ReentrantLock简介Synchronized对比用法源码分析代码结构方法分析SyncNonfairSyncFairSync非公平锁VS公平锁什么是公平非公平ReentrantLockReentrantLock的构造函数lock加锁方法...

    10、阻塞队列BlockingQueue实战及其原理分析.pdf

    7、深入理解 AQS 独占锁之 Reentrantlock 源码分析 (1).pdf 8、读写锁ReentrantReadWriteLock&StampLock详解.pdf 9、并发容器 (Map、List、Set) 实战及其原理.pdf 10、阻塞队列BlockingQueue 实战及其原理分析.pdf

    Java并发包源码分析(JDK1.8)

    Java并发包源码分析(JDK1.8):囊括了java.util.concurrent包中大部分类的源码分析,其中涉及automic包,locks包(AbstractQueuedSynchronizer、ReentrantLock、ReentrantReadWriteLock、LockSupport等),queue...

    JUC AQS(AbstractQueuedSynchronizer)

    ReentrantLock Lock 加锁过程源码分析图,AQS 源码分析

    6、JUC并发工具类在大厂的应用场景详解(1).pdf

    7、深入理解 AQS 独占锁之 Reentrantlock 源码分析 (1).pdf 8、读写锁ReentrantReadWriteLock&StampLock详解.pdf 9、并发容器 (Map、List、Set) 实战及其原理.pdf 10、阻塞队列BlockingQueue 实战及其原理分析.pdf

    9、并发容器(Map、List、Set)实战及其原理.pdf

    7、深入理解 AQS 独占锁之 Reentrantlock 源码分析 (1).pdf 8、读写锁ReentrantReadWriteLock&StampLock详解.pdf 9、并发容器 (Map、List、Set) 实战及其原理.pdf 10、阻塞队列BlockingQueue 实战及其原理分析.pdf

    8、读写锁ReentrantReadWriteLock&StampLock详解.pdf

    7、深入理解 AQS 独占锁之 Reentrantlock 源码分析 (1).pdf 8、读写锁ReentrantReadWriteLock&StampLock详解.pdf 9、并发容器 (Map、List、Set) 实战及其原理.pdf 10、阻塞队列BlockingQueue 实战及其原理分析.pdf

    Java并发编程学习笔记

    5、Condition源码分析 6、ReentrantReadWriteLock底层实现原理 7、并发工具类CountDownLatch 、CyclicBarrier和Semaphore底层实现原理 8、线程池原理和如何使用线程池 9、ThreadLocal 为什么会内存泄漏 10、Volatile...

    java8集合源码分析-Notes:笔记

    集合源码分析 [TOC] 0. 项目构建 0.1 版本控制 0.1.1 Git 0.2 项目管理 0.2.1 Maven 0.2.2 Gradle 1.:hot_beverage: Java 1.1 Java基础 1.1.1 算法与数据结构 字符串KMP算法 BitSet解决数据重复和是否存在等问题 ...

    jdk1.8-source:JDK1.8源码分析包

    JDK1.8源码分析 相关的原始码分析结果会以注解的形式体现到原始码中 已完成部分: ReentrantLock CountDownLatch Semaphore HashMap TreeMap LinkedHashMap ConcurrentHashMap 执行器 ...

    带你看看Java的锁(二)-Semaphore

    带你看看Java的锁-Semaphore前言简介使用源码分析类结构图SyncNonfairSyncFairSyncSemaphore 构造函数Semaphore 成员方法获取释放总结 前言 简介 Semaphore 中文称信号量,它和ReentrantLock 有所区别,...

    java8源码-thread-concurrent-study:线程并发研究

    HongJie《一行一行源码分析清除AbstractQueuedSynchronizer》 爱吃鱼的KK 《AbstractQueuedSynchronizer源码分析(基于Java8)》 waterstone《Java并发AQS详解》 英文论文的中文翻译: AQS作者的英文论文:

    汪文君高并发编程实战视频资源全集

     高并发编程第三阶段11讲 AtomicXXXFieldUpdater源码分析及使用场景分析.mp4  高并发编程第三阶段12讲 sun.misc.Unsafe介绍以及几种Counter方案性能对比.mp4  高并发编程第三阶段13讲 一个JNI程序的编写,通过...

    汪文君高并发编程实战视频资源下载.txt

     高并发编程第三阶段11讲 AtomicXXXFieldUpdater源码分析及使用场景分析.mp4  高并发编程第三阶段12讲 sun.misc.Unsafe介绍以及几种Counter方案性能对比.mp4  高并发编程第三阶段13讲 一个JNI程序的编写,通过...

    java线程池概念.txt

    这部分代码就不再追踪下去,有兴趣的读者可以自己打开源码分析,不必害怕,学习大神们的编码方式,看源码能让你学习到很多 } } private void runTask(Runnable task) { final ReentrantLock runLock = this....

    leetcode下载-studyday:记得我

    源码分析 AQS同步器原理(实现各种同步器)模板方法模式,继承并冲重写AQS方法 主要是加锁和解锁 java 创建线程池相关 done 不推荐使用Excutors工具类去创建默认的几种线程池。会有OOM风险...要么核心线程树可能过多...

Global site tag (gtag.js) - Google Analytics