java并发--ReentrantLock简单分析

ReentrantLock是java中并发包里的互斥锁,包含公平和非公平两种方式。内部是基于AQS实现的。实现了两个接口,Lock和Serializable。内部有个抽象类叫Sync。

 private final Sync sync;

    /**
     * Base of synchronization control for this lock. Subclassed
     * into fair and nonfair versions below. Uses AQS state to
     * represent the number of holds on the lock.
     */
    abstract static class Sync extends AbstractQueuedSynchronizer {
   

Sync集成了AQS,主要是负责锁的功能实现,在内部有两个实现类FairSync和NonFairSync,即公平锁和非公平锁。ReentrantLock的无参构造方法实例处理的就是NonFairSync,这个也是大部分时候使用的锁。

下面来看看ReentrantLock.lock方法

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

可以看到,ReentrantLock是直接委托给内部的sync设置加锁功能。

sync.lock是一个抽象方法,下面我们看常用的NonFairSync.lock方法

     final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

方法很简单,

  1. 首先用CAS把state设置为1,是否成功,成功的话就把当前线程设置为锁的拥有者
  2. 不成功的话就调用acquire(1);  acquire是在AQS里定义的,
        public final void acquire(int arg) {
            if (!tryAcquire(arg) &&
                acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
                selfInterrupt();
        }

    可以看到,acquire首先会调用tryAcquire方法,AQS并不实现tryAcquire方法,tryAcquire方法要各个子类实现,我们来看NonFairSync的tryAcquire方法
     

         protected final boolean tryAcquire(int acquires) {
                return nonfairTryAcquire(acquires);
            }
    
    
         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;
            }

    NonFairSync把tryAcquire直接转发到了nonfairTryAcquire方法。nonfairTryAcquire首先判断是否已经解锁,已经解锁的话就去尝试加锁,加锁成功的话就直接放回true。未解锁的话就判断这次操作是不是该线程重入操作,是重入操作的话就判断重入的操作次数是不是已经达到了Integer.MAX_VALUE,达到了就直接抛出异常,不然就再累加次数在把值设置给state属性。
    下面再来看看acquireQueued(addWaiter(Node.EXCLUSIVE), arg)方法,没有获取到锁的线程阻塞的效果就是acquireQueued方法里的for循环。
    addWaiter(Node.EXCLUSIVE)

     private Node addWaiter(Node mode) {
            Node node = new Node(Thread.currentThread(), mode);
            // Try the fast path of enq; backup to full enq on failure
            Node pred = tail;
            if (pred != null) {
                node.prev = pred;
                if (compareAndSetTail(pred, node)) {
                    pred.next = node;
                    return node;
                }
            }
            enq(node);
            return node;
        }

    ---待更新

  3.  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值