数据结构->并发之Lock

1.什么是锁?

  锁是用来控制多个线程访问共享资源的方式,一般来说,锁是用来防止多个线程同时获取共享资源。在java 1.5 之前,使用synchronized 关键字来实现锁的功能,1.5之后提供了lock 接口,虽然lock接口失去了synchronized 隐式获取和释放锁的便捷,但是

却提供了获取和释放锁的可操作性,可中断的获取锁以及超时获取锁等 synchronized 等不具备的同步特性

2.使用示例

Lock lock = new ReentrantLock();
lock.lock();
try{
	.......
}finally{
	lock.unlock();
}

注意:1.synchronized同步块执行完成或者遇到异常是锁会自动释放 而 lock必须调用unlock 方法释放锁,因此在finally块中释放锁

3.Lock 接口

public interface Lock {

   
//获取锁,如果锁不可用,当前线程被禁用以进行线程调度,在获取到锁之前,线程处于休眠状态
    void lock();

  //获取锁的过程能够响应线程中断,线程是可以被自己中断的 interupt 方法
    void lockInterruptibly() throws InterruptedException;

   //获取锁时锁是可用的立即返回true 否则立即返回false
    boolean tryLock();

   //如果线程在等待的时间内是空闲的并且未被中断则获取锁
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;

  //释放锁
    void unlock();

////获取与lock绑定的等待通知组件,当前线程必须持有锁才能进行等待,在开始等待之前会释放锁,在等待返回之前或重新获取锁
    Condition newCondition();
}

 

ReentrantLock 继承了lock
public class ReentrantLock implements Lock, java.io.Serializable {

   
  //获取锁,如果锁不可用,当前线程被禁用以进行线程调度,在获取到锁之前,线程处于休眠状态
    void lock(){
        sync.lock();
    }

  //获取锁的过程能够响应线程中断,线程是可以被自己中断的 interupt 方法
    void lockInterruptibly() throws InterruptedException{
         sync.acquireInterruptibly(1);
    }

   //获取锁时锁是可用的立即返回true 否则立即返回false
    boolean tryLock(){
        return sync.nonfairTryAcquire(1);
    }

   //如果线程在等待的时间内是空闲的并且未被中断则获取锁
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException{
       
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

  //释放锁
    void unlock(){
      sync.release(1);
    }

////获取与lock绑定的等待通知组件,当前线程必须持有锁才能进行等待,在开始等待之前会释放锁,在等待返回之前或重新获取锁
    Condition newCondition(){
          return sync.newCondition();
    }
}

 可以看出ReentrantLock 实际是面向使用者的一个封装类,lock真正的实现是由sync 来实现的,通过源码发现这些并不是sync自己实现的而是它的父类 AbstractQueuedSynchronizer(队列同步器AQS)实现的.

AQS 数据结构

struct Node{
    struct Node * pre;//前驱节点
    struct Node * pNext;//后继节点
    int waitStatus;
    Thread * thread;//线程
    struct Node * nextWaiter;// 模式 Node.EXCLUSIVE 独占, Node.SHARED 共享
}

队列
struct stack{
 struct Node * pHead;
 struct Node * pTail;
 int state //当前同步状态
}

//双链表实现的队列
//1.初始化和2.入队 同时实现的
   private Node enq(final Node node) {
//自旋
        for (;;) {
            Node t = tail;
//尾节点为空则创建一个节点设置为头节,并将尾节点指向头节点
//头节点、尾节点只是为了方便操作
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
//1.将插入的节点的前驱节点指向尾节点 2.将插入的节点设置为新的尾节点3.将之前的尾节点后继节点指向 插入的节点

                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }
//3.出队

1.直接从lock.lock() 入手

 /**
     * Sync object for non-fair locks
     */
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
            //如果state 的值是0,初始化为0,直接将当前线程设置为独有访问权限的线程,将状态设置为1
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else//否则执行acquire
                acquire(1);
        }

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

这里要引入 Unsafe.objectFieldOffset(Field),注释说是为了CAS 操作必须初始化一些参数,这应该是属性的内存编号偏移量

static {
        try {
            stateOffset = unsafe.objectFieldOffset
                (AbstractQueuedSynchronizer.class.getDeclaredField("state"));
            headOffset = unsafe.objectFieldOffset
                (AbstractQueuedSynchronizer.class.getDeclaredField("head"));
            tailOffset = unsafe.objectFieldOffset
                (AbstractQueuedSynchronizer.class.getDeclaredField("tail"));
            waitStatusOffset = unsafe.objectFieldOffset
                (Node.class.getDeclaredField("waitStatus"));
            nextOffset = unsafe.objectFieldOffset
                (Node.class.getDeclaredField("next"));

        } catch (Exception ex) { throw new Error(ex); }
    }

2.acquire()

  public final void acquire(int arg) {
//如果不能将当前线程设置为独占队列同步器访问权限的线程,即未获取到锁
// 执行addWaiter 并执行acquireQueued 方法
// acquireQueued 会一直阻塞直到产生的新节点的前驱节点是头节点并且状态为signal
//如果在阻塞过程中当前线程出现过中断 那么会重新产生一个中断
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

tryAcquire() 的实现调用
final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            //获取当前同步状态
            int c = getState();
            if (c == 0) {
            //如果当前状态是0 直接将状态更新为1 并将当前线程设置为同步器独占访问权限的线程
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
//如果当前线程独占访问权限的线程,并且状态不为0
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
//将状态设置为c + acquires(acquires = 1)
                setState(nextc);
                return true;
            }
//否则返回false
            return false;
        }

//三种情况:1. state == 0,直接将当前线程设置为独占访问权限的线程,将状态改为acquires,从 
 //lock.lock() 那里走过来,acquires的值为1->state =1,返回true;
//2.state != 0 并且 当前线程就是独占访问权限的线程,如果state+1 <0 抛异常,否则将state设 
 //置为state+1,返回true
 //3. 其他情况返回false

addWaiter(Node.EXCLUSIVE){
//将thread 封装成一个 node
     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;

}


final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {//自旋
                //当前节点的前驱节点
                final Node p = node.predecessor();
                //如果当前节点的前驱节点是头节点将尝试获取锁
                //1.如果获取到锁 将当前节点设置为头节点
                //断开之前头节点指向当前节点的指针,方便内存回收,返回false
                //相当于出队
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                //2.其他任何情况,在node 的前驱成为头节点之前会无线循环检查线程是否中断
                //如果已经中断第二次检查的时候会返回false
                  
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

   /** 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;

//如果线程应该阻塞返回true 否则false
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
//pred 是node 的前驱节点
        int ws = pred.waitStatus;
//如果前驱节点的状态已经是Node.SIGNAL 返回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) {//大于1 只有一种情况 cancelled
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            do {
//如果前驱节点被取消,将node 的前驱节点指向 pred 的前一个节点,但是pred 的后一个节点仍旧指向node,这样会导致最多2个节点的后继指向node
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
//将pred 的后继节点指向node
            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.
             */
//将前驱节点的状态设置为SIGNAL 等待
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

   /**
     * Convenience method to park and then check if interrupted
     *
     * @return {@code true} if interrupted
     */
    private final boolean parkAndCheckInterrupt() {
        //禁用当前线程进行线程调度,并让当前线程处于休眠状态直到被唤醒(unpark,interupt)
        LockSupport.park(this);
        return Thread.interrupted();//如果当前线程是中断状态调用之后会清除状态,第二次返回false
    }
//线程的中断只是将中断标志位设为true 当调用类似wait sleep 方法的时候会抛出异常并重置
//中断为false 唤醒线程,

//当node 的前驱成为头节点的时候,中断当前线程
    static void selfInterrupt() {
        Thread.currentThread().interrupt();
    }


//独占模式的释放-> 释放头节点,直到队列同步器free 才算完全释放
    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;
//如果state == 0 将队列同步器设置为空闲状态,将独占访问权限的线程置为空
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
//将状态设置为 state - 1
            setState(c);
            return free;
        }

总结:每次调用lock.lock 的时候都会将state +1,释放的时候减一

//node 为头节点
 private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
//不为cancelled 将waitStatus 设置为0 初始化状态
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        //头节点的后继节点
        Node s = node.next;
        //找到没有cancel 的后继节点
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        //唤醒该线程
        if (s != null)
            LockSupport.unpark(s.thread);
    }

总结:

独占式锁按照队列的排列顺序获取锁

1.调用lock.lock() 的时候,先检查队列是否有初始化,没初始化先初始化队列的头节点,然后将当前线程封装成一个node(节点)插入在队列末尾,如果已经初始化,并且当前线程就是持有锁的线程,将state 设置成state+1。其他情况会尝试获取锁(state == 0 或者当前线程是持有锁的线程才会获取到锁)将当前线程封装成node(节点) 插入队列末尾,并且让当前线程休眠,将node 的状态waitstatus设置成singal。如果获取到锁会将头节点出队,并将当前节点设置为头节点。

 2.当前持有锁的节点(头节点)的线程不会休眠,当你手动unlock 的时候,会释放锁,此时会unpark 唤醒下个节点的线程

总体来说:在获取同步状态时,AQS维护一个同步队列,获取同步状态失败的线程会加入到队列中进行自旋;移除队列(或停止自旋)的条件是前驱节点是头结点并且成功获得了同步状态。在释放同步状态时,同步器会调用unparkSuccessor()方法唤醒后继节点。

 

可中断获取锁lock.lockInterruptibly()

  public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    public final void acquireInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (!tryAcquire(arg))//没有获取到锁
            doAcquireInterruptibly(arg);
    }

 private void doAcquireInterruptibly(int arg)
        throws InterruptedException {
//将当前线程封装成node 加入到队列末尾
        final Node node = addWaiter(Node.EXCLUSIVE);
        boolean failed = true;
        try {
            //自旋
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                   //出队
                    p.next = null; // help GC
                    failed = false;
                    return;
                }
                //将p 的waitstatus设置为singal 让当前线程休眠
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    //当线程中断的时候抛出异常
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

 超时等待式获取锁(tryAcquireNanos()方法)

通过调用lock.tryLock(timeout,TimeUnit)方式达到超时等待获取锁的效果,该方法会在三种情况下才会返回:

  1. 在超时时间内,当前线程成功获取了锁;
  2. 当前线程在超时时间内被中断;
  3. 超时时间结束,仍未获得锁返回false。
      public final boolean tryAcquireNanos(int arg, long nanosTimeout)
                throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            return tryAcquire(arg) ||
                doAcquireNanos(arg, nanosTimeout);
        }
    
    
    
      private boolean doAcquireNanos(int arg, long nanosTimeout)
                throws InterruptedException {
            if (nanosTimeout <= 0L)
                return false;
            //计算超时时间
            final long deadline = System.nanoTime() + nanosTimeout;
            //将当前线程封装成node 入队
            final Node node = addWaiter(Node.EXCLUSIVE);
            boolean failed = true;
            try {
                for (;;) {
                    final Node p = node.predecessor();
                    if (p == head && tryAcquire(arg)) {
                        //获取到锁就让头节点出队,把自己设成头节点
                        setHead(node);
                        p.next = null; // help GC
                        failed = false;
                        return true;
                    }
                    //计算超时时间间隔
                    nanosTimeout = deadline - System.nanoTime();
                    if (nanosTimeout <= 0L)//表示已经超时
                        return false;
                    if (shouldParkAfterFailedAcquire(p, node) &&
                        nanosTimeout > spinForTimeoutThreshold)
                        //这段时间间隔之内当前线程不可调度,休眠
                        LockSupport.parkNanos(this, nanosTimeout);
                    if (Thread.interrupted())
                        throw new InterruptedException();
                }
            } finally {
                if (failed)
                    cancelAcquire(node);
            }
        }

     

  疑问1.LockSupport.park 到底是干什么的?文档上说以下三种情况会返回,否则会调用pthread.wait 进入等待状态

1.Some other thread invokes unpark with the current thread as the target;//调用了unparkSome

2.other thread interrupts the current thread; or// 调用了线程的interrupt

3.The call spuriously (that is, for no reason) returns.//莫名其妙的返回

所以那个自旋在线程进入wait 状态之后并没有继续执行,直到unpark 或者interrupt,当线程在wait状态被中断的时候 线程会被唤醒进入自旋并抛出异常,所以如果线程中断都是立即抛出异常的。

疑问2.这些没获取到同步状态的节点是怎么出队的?

那些返回false 将 cancelAcquire 出队

    private void cancelAcquire(Node node) {
        // Ignore if node doesn't exist
        if (node == null)
            return;

        node.thread = null;

        // Skip cancelled predecessors
        Node pred = node.prev;
        while (pred.waitStatus > 0)
            node.prev = pred = pred.prev;

        // predNext is the apparent node to unsplice. CASes below will
        // fail if not, in which case, we lost race vs another cancel
        // or signal, so no further action is necessary.
        Node predNext = pred.next;

        // Can use unconditional write instead of CAS here.
        // After this atomic step, other Nodes can skip past us.
        // Before, we are free of interference from other threads.
        node.waitStatus = Node.CANCELLED;

        // If we are the tail, remove ourselves.
        if (node == tail && compareAndSetTail(node, pred)) {
            pred.compareAndSetNext(predNext, null);
        } else {
            // If successor needs signal, try to set pred's next-link
            // so it will get one. Otherwise wake it up to propagate.
            int ws;
            if (pred != head &&
                ((ws = pred.waitStatus) == Node.SIGNAL ||
                 (ws <= 0 && pred.compareAndSetWaitStatus(ws, Node.SIGNAL))) &&
                pred.thread != null) {
                Node next = node.next;
                if (next != null && next.waitStatus <= 0)
                    pred.compareAndSetNext(predNext, next);
            } else {
                unparkSuccessor(node);
            }

            node.next = node; // help GC
        }
    }

 

 

共享锁

  public final void acquireShared(int arg) {
        //tryAcquireShared 没找到有实现这个方法的类
        if (tryAcquireShared(arg) < 0)
            doAcquireShared(arg);
    }

  private void doAcquireShared(int arg) {
       //加入队列
        final Node node = addWaiter(Node.SHARED);
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        //获取到锁将头节点出队,让当前节点成为头节点
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        //如果线程中断过再次调用interrupt
                        if (interrupted)
                            selfInterrupt();
                        return;
                    }
                }
                //将头节点的waitstatus 设置为signal 让当前线程进入wait
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } catch (Throwable t) {
            cancelAcquire(node);
            throw t;
        }
    }

    public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }

 private void doReleaseShared() {
        /*
         * Ensure that a release propagates, even if there are other
         * in-progress acquires/releases.  This proceeds in the usual
         * way of trying to unparkSuccessor of head if it needs
         * signal. But if it does not, status is set to PROPAGATE to
         * ensure that upon release, propagation continues.
         * Additionally, we must loop in case a new node is added
         * while we are doing this. Also, unlike other uses of
         * unparkSuccessor, we need to know if CAS to reset status
         * fails, if so rechecking.
         */
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!h.compareAndSetWaitStatus(Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !h.compareAndSetWaitStatus(0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }

//唤醒下个节点的线程
 private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0)
            node.compareAndSetWaitStatus(ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        Node s = node.next;
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node p = tail; p != node && p != null; p = p.prev)
                if (p.waitStatus <= 0)
                    s = p;
        }
        if (s != null)
            LockSupport.unpark(s.thread);
    }

没找到共享锁的实现,但方式差不多,获取到锁将当前节点设置为头节点,前任头节点出队

总结:将java源码以数据结构的方式打开,队列同步器 不过是一个队列,指定了入队出队的方式,头节点能获取到锁,其他节点无法获取到锁,其他节点关联的线程进入等待状态,直到头节点释放锁出队,新的头节点获取到锁并唤醒线程。无法获取到的锁的节点会cancelAquire 出队

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章