AmazingCounters.com

ReentrantLock总体概括

一、锁的实现原理:
JAVA concurrent包下面的锁是通过AbstractQueuedSynchronizer内的Node类下面的state属性来实现的,并且锁的可重入属性也是通过state实现的。

先来看看这个state的定义:

   /**
     * The synchronization state.
     */
    private volatile int state;

同步的状态,是一个volatile修饰的私有整形变量,volatile修饰的变量是一个多线程可见的,但是多线程可见,并不能保证操作是原子的。在AbstractQueuedSynchronizer下的compareAndSetState方法保证了操作的原子性,volatile 和 CAS的结合是并发抢占的关键。

 /**
     * Atomically sets synchronization state to the given updated
     * value if the current state value equals the expected value.
     * This operation has memory semantics of a {@code volatile} read
     * and write.
     *
     * @param expect the expected value
     * @param update the new value
     * @return {@code true} if successful. False return indicates that the actual
     *         value was not equal to the expected value.
     */
    protected final boolean compareAndSetState(int expect, int update) {
        // See below for intrinsics setup to support this
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }

 

二、可重入锁中的几个概念

查看源码可以看出来,在ReentrantLock内部有一个抽象类sync继承了AbstractQueuedSynchronizer,并且有两个实现,分别是:FairSync,其实就是竞争锁的机制是公平的,公平体现在按照请求的顺序把锁在队列中的线程节点中传递下去,NonfairSync:谁先抢占了state,谁就获得锁,并且一旦加入到队列中就要按照顺序来拿锁。

FairSync:锁的访问会按照线程的请求顺序,一个线程一个线程的往下面传递。这种传递的属性是通过将线程封装成Node,并且加入到链表中的方式实现的。

线程被封装的方式:

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

NonfairSync:锁被释放了之后,谁先获取到锁谁就拥有锁。

非公平锁的效率会比公平锁的实现效率高。

对于非公平锁来说,如果线程加入到了队列(被封装成线程的一个一个Node)中,想要获取到锁,就要按照队列的顺序取获取,但是如果有其他的线程想要获取锁,那么队列中的线程竞争的锁,没有其他线程获取到的机率大。

 

posted @ 2018-03-19 08:03  若谷先生  阅读(158)  评论(0编辑  收藏  举报