Java中ReentrantLock底层原理

ReentrantLock底层原理

ReentranLock是一个支持重入的独占锁,在java.util.concurrent包中,底层就是基于AQS实现的,因此下面会设计到AQS的一些东西,若是还不了解的能够先看这篇 Java AQS底层原理解析 了解一下。java

  • Sync类segmentfault

    在源码中能够看到ReentrantLock类自己并无继承AQS,而是建立了一个内部类Sync来继承AQS,而ReentrantLock类自己的那些方法都是调用Sync里面的方法来实现,而Sync自己本身也是一个抽象类,它还有两个子类,分别是NonfairSyncFairSync,对锁各类实际的实现其实在这两个类中实现,顾名思义,这两个类分别实现了非公平锁和公平锁,在建立ReentrantLock时能够进行选择。函数

    // 默认构造函数是建立一个非公平锁
    public ReentrantLock() {
        sync = new NonfairSync();
    }
    
    // 接受一个boolean参数,true是建立公平锁,false是非公平锁
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }
  • lock()ui

    • 会调用Sync类中的lock()方法,因此须要看建立的是公平锁仍是非公平锁this

      public void lock() {
          sync.lock();
      }
    • 非公平锁中的lock()方法,先试用CAS的方式更新AQS中的state的状态,默认是0表明没有被获取,当前线程就能够获取锁,而后把state改成1,接着把当前线程标记为持有锁的线程,若是if中的操做失败就表示锁已经被持有了,就会调用acquire()方法线程

      final void lock() {
          if (compareAndSetState(0, 1))
              setExclusiveOwnerThread(Thread.currentThread());
          else
              acquire(1);
      }
    • acquire()方法是AQS中的那个方法,这里面调用子类实现的tryAcquire()方法,最终是调用到Sync类中的nonfairTryAcquire()方法,能够看到先判断state是否是0,也就是能不能获取锁,若是不能则判断请求锁的线程和持有锁的是否是同一个,若是是的话就把state的值加1,也就是实现了重入锁设计

      public final void acquire(int arg) {
          if (!tryAcquire(arg) &&
              acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
              selfInterrupt();
      }
      
      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;
      }
    • 重写的tryAcquire()方法,上面非公平锁是调用的Sync里的tryAcquire()方法,而公平锁则在子类NonfairSync中重写了这个方法,注意if(c==0)判断中的代码,也就是线程抢夺锁的时候会调用hasQueuedPredecessors()方法,这个方法会判断队列中有没有已经先等待的线程了,若是有则当前线程不会抢到锁,这就实现了公平性,上面nonfairTryAcquire()方法则没有这种判断,因此后来的线程可能会比先等待的线程先拿到锁code

      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;
      }
      
      public final boolean hasQueuedPredecessors() {
          // The correctness of this depends on head being initialized
          // before tail and on head.next being accurate if the current
          // thread is first in queue.
          Node t = tail; // Read fields in reverse initialization order
          Node h = head;
          Node s;
          return h != t &&
              ((s = h.next) == null || s.thread != Thread.currentThread());
      }
  • tryLock()继承

    这个方法是尝试去获取锁,若是成功返回true,失败则返回false。会发现调用的就是上面Sync中的nonfairTryAcquire()方法队列

    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }
  • unlock()

    这个方法是释放锁,最终会调用到Sync类中的tryRelease()方法。在这个方法里面会对state减1,若是减1以后为0就表示当前线程持有次数完全清空了,须要释放锁

    public void unlock() {
        sync.release(1);
    }
    
    public final boolean release(int arg) {
        if (tryRelease(arg)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);
            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;
    }

总结:

若是看了 Java AQS底层原理解析 这篇文章,就会发现其实JUC中的不少锁都是在AQS的基础上实现的,并且最复杂的逻辑也是在AQS中实现的,这些锁只是在它的基础上实现本身的需求。