ReentrantLock

来源:互联网 发布:淘宝关于dns劫持的教程 编辑:程序博客网 时间:2024/05/01 15:21

title:ReentrantLock

date:2017年11月12日12:40:32


​ 在生产者消费者问题中,我们提到了利用锁和Condition条件来解决问题。

今天我们就来看下锁是怎么实现的。

private final Lock lock=new ReentrantLock();lock.lock();

ReentrantLock锁在同一个时间点只能被一个线程锁持有;而可重入的意思是,ReentrantLock锁,可以被单个线程多次获取。
ReentrantLock分为“公平锁”和“非公平锁”。它们的区别体现在获取锁的机制上是否公平。“锁”是为了保护竞争资源,防止多个线程同时操作线程而出错,ReentrantLock在同一个时间点只能被一个线程获取(当某线程获取到“锁”时,其它线程就必须等待);ReentraantLock是通过一个FIFO的等待队列来管理获取该锁所有线程的。在“公平锁”的机制下,线程依次排队获取锁;而“非公平锁”在锁是可获取状态时,不管自己是不是在队列的开头都会获取锁。

当new RReentrantLock();的时候,默认使用非公平锁。

  private final Sync sync;  public ReentrantLock() {        sync = new NonfairSync();    }

当创建一个实例的时候,在构造方法里里面创建了一个NonfairSync对象。

NonfairSync是ReentrantLock中的一个静态内部类,他继承了Sync类。而Sync是ReentrantLock中的一个静态类,而且是abstract修饰的抽象类,他继承了AbstractQueuedSynchronizer,这个类就是AQS,

它是一个非常有用的超类,可用来定义锁以及依赖于排队阻塞线程的其他同步器;ReentrantLock,ReentrantReadWriteLock,CountDownLatch,CyclicBarrier和Semaphore等这些类都是基于AQS类实现的。AbstractQueuedLongSynchronizer 类提供相同的功能但扩展了对同步状态的 64 位的支持。两者都扩展了类 AbstractOwnableSynchronizer(一个帮助记录当前保持独占同步的线程的简单类)。

    abstract static class Sync extends AbstractQueuedSynchronizer {        private static final long serialVersionUID = -5179523762034025860L;        /**         * Performs {@link Lock#lock}. The main reason for subclassing         * is to allow fast path for nonfair version.         */        abstract void lock();        /**         * Performs non-fair tryLock.  tryAcquire is implemented in         * subclasses, but both need nonfair try for trylock method.         */        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;        }        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;        }        protected final boolean isHeldExclusively() {            // While we must in general read state before owner,            // we don't need to do so to check if current thread is owner            return getExclusiveOwnerThread() == Thread.currentThread();        }        final ConditionObject newCondition() {            return new ConditionObject();        }        // Methods relayed from outer class        final Thread getOwner() {            return getState() == 0 ? null : getExclusiveOwnerThread();        }        final int getHoldCount() {            return isHeldExclusively() ? getState() : 0;        }        final boolean isLocked() {            return getState() != 0;        }        /**         * Reconstitutes the instance from a stream (that is, deserializes it).         */        private void readObject(java.io.ObjectInputStream s)            throws java.io.IOException, ClassNotFoundException {            s.defaultReadObject();            setState(0); // reset to unlocked state        }    }
  • 接着我们来看看lock.lock()到底的具体实现是什么:
  public void lock() {        sync.lock();    }

默认是使用的非公平锁,则sync.lock()的具体实现为:

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

我们分析下这个方法

lock()会先通过compareAndSet(0, 1)来判断“锁”是不是空闲状态。是的话,“当前线程”直接获取“锁”;否则的话,调用acquire(1)获取锁。

(01) compareAndSetState()是CAS函数,它的作用是比较并设置当前锁的状态。若锁的状态值为0,则设置锁的状态值为1。

compareAndSetState()在AQS中实现。它的源码如下:

        // See below for intrinsics setup to support this        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);    }

compareAndSwapInt() 是sun.misc.Unsafe类中的一个本地方法。对此,我们需要了解的是 compareAndSetState(expect, update) 是以原子的方式操作当前线程;若当前线程的状态为expect,则设置它的状态为update。我们要明白AQS在实现锁和阻塞队列时时非常有用的类。

(02) setExclusiveOwnerThread(Thread.currentThread())的作用是,设置“当前线程”为“锁”的持有者。

  • acquire()方法

    public final void acquire(int arg) {      if (!tryAcquire(arg) &&          acquireQueued(addWaiter(Node.EXCLUSIVE), arg))          selfInterrupt();  }

    acquire()方法也是在AQS中实现的,不得不说,在任何框架,甚至JDK的设计中,都大量的运用到了模板方法设计模式。

    • 当前前程首先通过tryAcquire()尝试获取锁,获取成功的话,直接返回。获取失败的话,

    进入到等待队列依次排序,然后获取锁。

    这里再说一下这句代码的设计:

     if (!tryAcquire(arg) &&            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))

    这里if里面的是与逻辑,我们在学习&&逻辑符号的时候就说过,&&具有短路功能,也就是说只有第一个分支是true才会执行第二个,如果第一个分支(这里是!tryAcquire(arg))是false的话,就会直接跳出if了,而在这里就是直接返回了。这里就有点类似于if return 提前返回。

    if(flag){  return;}.......

    这里JDK这样的设计也是蛮有灵性的。

  • tryAcquire()方法

       protected final boolean tryAcquire(int acquires) {          return nonfairTryAcquire(acquires);      }

    tryAcquire()方法在AOS中是一个抽象方法,在非公平锁中,具体实现在NonfairSync这个静态内部类中。

    protected final boolean tryAcquire(int acquires) {          return nonfairTryAcquire(acquires);      }      final boolean nonfairTryAcquire(int acquires) {        //获取当前线程          final Thread current = Thread.currentThread();        //获取锁的状态          int c = getState();           // c=0意味着锁没有被任何线程锁拥有          if (c == 0) {            // 若“锁没有被任何线程锁拥有”,则通过CAS函数设置锁的状态为acquires。      // 同时,设置当前线程为锁的持有者。                   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;      } 

    • getState(), setState()

    getState()和setState()都在AQS中实现,源码如下:

    // 锁的状态private volatile int state;// 设置锁的状态protected final void setState(int newState) {    state = newState;}// 获取锁的状态protected final int getState() {    return state;}

    state表示锁的状态,对于“独占锁”而已,state=0表示锁是可获取状态(即,锁没有被任何线程锁持有)。由于java中的独占锁是可重入的,state的值可以>1。

    tryAcquire()的作用就是让当前线程尝试获取锁。获取成功返回true,失败则返回false。返回false之后,if的第一分支就是true,此时会执行第二分支 acquireQueued(addWaiter(Node.EXCLUSIVE), arg)

  • addWaite()方法

    在说acquireQueued()方法之前需要说明下他的第一个参数的方法addWaiter()

    addWaiter()方法的实现是在AQS中。

      private Node addWaiter(Node mode) {    //新建一个Node节点,node节点对应的是当前线程,当前线程锁的模型是Node.EXCLUSIVE      Node node = new Node(Thread.currentThread(), mode);      // Try the fast path of enq; backup to full enq on failure//取CLH队列的末尾元素            Node pred = tail;    //如果末尾元素不为null,即CLH队列不为空,则将node节点插入在CLH阻塞队列末尾      if (pred != null) {          node.prev = pred;          if (compareAndSetTail(pred, node)) {              pred.next = node;              return node;          }      }        // 若CLH队列为空,则调用enq()新建CLH队列,然后再将当前线程添加到CLH队列中。      enq(node);      return node;  }private Node enq(final Node node) {      for (;;) {          Node t = tail;          if (t == null) { // Must initialize              if (compareAndSetHead(new Node()))                  tail = head;          } else {              node.prev = t;              if (compareAndSetTail(t, node)) {                  t.next = node;                  return t;              }          }      }  }

​ 1.compareAndSetTail()

 private final boolean compareAndSetTail(Node expect, Node update) {        return unsafe.compareAndSwapObject(this, tailOffset, expect, update);    }

compareAndSetTail()也是在AQS中实现的,也属于CAS函数,也是通过本地native方法实现的。compareAndSetTail(expect, update)会以原子的方式进行操作,它的作用是判断CLH队列的队尾是不是为expect,是的话,就将队尾设为update。

​ 2.enq()

enq()的作用很简单。如果CLH队列为空,则新建一个CLH表头;然后将node添加到CLH末尾。否则,直接将node添加到CLH末尾

​ 3.Node类

Node就是CLH队列的节点。Node在AQS中实现,是AQS的静态内部类

注: CLH队列是AQS中“等待锁”的线程队列。在多线程中,为了保护竞争资源不被多个线程同时操作而起来错误,我们常常需要通过锁来保护这些资源。在独占锁中,竞争资源在一个时间点只能被一个线程锁访问;而其它线程则需要等待。CLH就是管理这些“等待锁”的线程的队列。
    CLH是一个非阻塞的 FIFO 队列。也就是说往里面插入或移除一个节点的时候,在并发条件下不会阻塞,而是通过自旋锁和 CAS 保证节点插入和移除的原子性。

CAS函数:

CAS函数,是比较并交换函数,它是原子操作函数;即,通过CAS操作的数据都是以原子方式进行的。例如,compareAndSetHead(), compareAndSetTail(), compareAndSetNext()等函数。它们共同的特点是,这些函数所执行的动作是以原子的方式进行的。

private transient volatile Node head;    // CLH队列的队首private transient volatile Node tail;    // CLH队列的队尾// CLH队列的节点static final class Node {    static final Node SHARED = new Node();    static final Node EXCLUSIVE = null;    // 线程已被取消,对应的waitStatus的值    static final int CANCELLED =  1;    // “当前线程的后继线程需要被unpark(唤醒)”,对应的waitStatus的值。    // 一般发生情况是:当前线程的后继线程处于阻塞状态,而当前线程被release或cancel掉,因此需要唤醒当前线程的后继线程。    static final int SIGNAL    = -1;    // 线程(处在Condition休眠状态)在等待Condition唤醒,对应的waitStatus的值    static final int CONDITION = -2;    // (共享锁)其它线程获取到“共享锁”,对应的waitStatus的值    static final int PROPAGATE = -3;    // waitStatus为“CANCELLED, SIGNAL, CONDITION, PROPAGATE”时分别表示不同状态,    // 若waitStatus=0,则意味着当前线程不属于上面的任何一种状态。    volatile int waitStatus;    // 前一节点    volatile Node prev;    // 后一节点    volatile Node next;    // 节点所对应的线程    volatile Thread thread;    // nextWaiter是“区别当前CLH队列是 ‘独占锁’队列 还是 ‘共享锁’队列 的标记”    // 若nextWaiter=SHARED,则CLH队列是“独占锁”队列;    // 若nextWaiter=EXCLUSIVE,(即nextWaiter=null),则CLH队列是“共享锁”队列。    Node nextWaiter;    // “共享锁”则返回true,“独占锁”则返回false。    final boolean isShared() {        return nextWaiter == SHARED;    }    // 返回前一节点    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    }    // 构造函数。thread是节点所对应的线程,mode是用来表示thread的锁是“独占锁”还是“共享锁”。    Node(Thread thread, Node mode) {     // Used by addWaiter        this.nextWaiter = mode;        this.thread = thread;    }    // 构造函数。thread是节点所对应的线程,waitStatus是线程的等待状态。    Node(Thread thread, int waitStatus) { // Used by Condition        this.waitStatus = waitStatus;        this.thread = thread;    }}

Node是CLH队列的节点,代表“等待锁的线程队列”。
(01) 每个Node都会一个线程对应。
(02) 每个Node会通过prev和next分别指向上一个节点和下一个节点,这分别代表上一个等待线程和下一个等待线程。
(03) Node通过waitStatus保存线程的等待状态。
(04) Node通过nextWaiter来区分线程是“独占锁”线程还是“共享锁”线程。如果是“独占锁”线程,则nextWaiter的值为EXCLUSIVE;如果是“共享锁”线程,则nextWaiter的值是SHARED。

  • acquireQueued()方法

    该方法依旧是在AQS中实现的:

    final boolean acquireQueued(final Node node, int arg) {      boolean failed = true;      try {          boolean interrupted = false;        //使用无限循坏,直到return返回          for (;;) {            //定位到当前线程对应节点在CLH的前继节点,              final Node p = node.predecessor();            //如果前继节点是头结点,且当前锁尝试获取锁成功,才会return,才会退出这个方法           //将当前节点设置为头节点,返回false,即第二个逻辑判断分支也为false,     //lock.lock()得以返回,因为在tryAcquire(arg)中以及成功获取锁了              if (p == head && tryAcquire(arg)) {                    //设置为头结点                setHead(node);                  p.next = null; // help GC                  failed = false;                  return interrupted;              }            //否则,执行shouldParkAfterFailedAcquire,这个方法需要具体分析              if (shouldParkAfterFailedAcquire(p, node) &&                  parkAndCheckInterrupt())                  interrupted = true;          }      } finally {          if (failed)              cancelAcquire(node);      }  }

    由上面代码中的分析可见,acquireQueued()的目的是从CLH队列中获取锁。

  • shouldParkAfterFailedAcquire()

shouldParkAfterFailedAcquire

private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {        //取出当前线程前继节点表示的状态        int ws = pred.waitStatus;  //如果前继节点是SIGNAL状态,则意味这当前线程需要被unpark唤醒。此时,返回true。        if (ws == Node.SIGNAL)            /*             * This node has already set status asking a release             * to signal it, so it can safely park.             */            return true;        if (ws > 0) {            /*             * Predecessor was cancelled. Skip over predecessors and             * indicate retry.             */             // 如果前继节点是“取消”状态,则设置 “当前节点”的 “当前前继节点”  为  “‘原前继节点’的前继节点”。就是删除了前继节点            do {                node.prev = pred = pred.prev;            } while (pred.waitStatus > 0);            pred.next = node;        } else {            /*             * waitStatus must be 0 or PROPAGATE.  Indicate that we             * need a signal, but don't park yet.  Caller will need to             * retry to make sure it cannot acquire before parking.             */        // 如果前继节点为“0”或者“共享锁”状态,则设置前继节点为SIGNAL状态。显然这也是一个CAS函数            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);        }        return false;    }

shouldParkAfterFailedAcquire()方法是通过如下流程判断当前线程是否需要被阻塞的。

1、如果前继节点状态为SIGNAL,表明当前节点需要被unpark(唤醒),此时则返回true2、如果前继节点状态为CANCELLED(ws>0),说明前继节点已经被取消,则通过先前回溯找到一个有效(非CANCELLED状态)的节点,并返回false3、如果前继节点状态为非SIGNAL、非CANCELLED,则设置前继的状态为SIGNAL,并返回false

如果1发生了返回true,则会执行parkAndCheckInterrupt()来阻塞当前线程。

  • parkAndCheckInterrupt()

    该方法依然是在AQS中实现的。

    private final boolean parkAndCheckInterrupt() {      LockSupport.park(this);      return Thread.interrupted();  }

    parkAndCheckInterrupt()的作用是阻塞当前线程,并且返回线程被唤醒之后的中断状态。
    它会先通过LockSupport.park()阻塞当前线程,然后通过Thread.interrupted()返回线程的中断状态。注意:Thread.interrupted()方法会清空线程中断状态。

    这里介绍一下线程被阻塞之后如何唤醒。一般有2种情况:
    第1种情况:unpark()唤醒。“前继节点对应的线程”使用完锁之后,通过unpark()方式唤醒当前线程。
    第2种情况:中断唤醒。其它线程通过interrupt()中断当前线程。

    补充:LockSupport()中的park(),unpark()的作用 和 Object中的wait(),notify()作用类似,是阻塞/唤醒。
    它们的用法不同,park(),unpark()是轻量级的,而wait(),notify()是必须先通过Synchronized获取同步锁。

  • selfInterrupt()

    selfInterrupt() 依然是在AQS中实现的,这里是让当前线程自行中断,当调用parkAndCheckInterrupt()返回true后,会执行这个方法,这个方法就是让线程再中断一次,之所以需要重新中断一次,是因为parkAndCheckInterrupt()中调用Thread.interrupted会清空中断标志,即在该线程“成功获取锁并真正执行起来”之前,它的中断会被忽略并且中断标记会被清除!

      static void selfInterrupt() {      Thread.currentThread().interrupt();  }
  • 总结

    再回过头看看acquire()函数,它最终的目的是获取锁!

(01) 先是通过tryAcquire()尝试获取锁。获取成功的话,直接返回;尝试失败的话,再通过acquireQueued()获取锁。
(02) 尝试失败的情况下,会先通过addWaiter()来将“当前线程”加入到”CLH队列”末尾;然后调用acquireQueued(),在CLH队列中排序等待获取锁,在此过程中,线程处于休眠状态。直到获取锁了才返回。 如果在休眠等待过程中被中断过,则调用selfInterrupt()来自己产生一个中断。

原创粉丝点击