`
lionlx
  • 浏览: 288561 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

(转)ReentrantLock代码剖析之ReentrantLock.lockInterruptibly

 
阅读更多
ReentrantLock.lockInterruptibly允许在等待时由其它线程调用等待线程的Thread.interrupt方法来中断等待线程的等待而直接返回,这时不用获取锁,而会抛出一个InterruptedException。而ReentrantLock.lock方法不允许Thread.interrupt中断,即使检测到Thread.isInterrupted,一样会继续尝试获取锁,失败则继续休眠。只是在最后获取锁成功后再把当前线程置为interrupted状态。

那lockInterruptibly是如何做到这一点的?

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

这里调用了AbstractQueuedSynchronizer.acquireInterruptibly方法。如果线程已被中断则直接抛出异常,否则则尝试获取锁,失败则doAcquireInterruptibly

AbstractQueuedSynchronizer.acquireInterruptibly(int arg)
 /**
     * Acquires in exclusive mode, aborting if interrupted.
     * Implemented by first checking interrupt status, then invoking
     * at least once {@link #tryAcquire}, returning on
     * success.  Otherwise the thread is queued, possibly repeatedly
     * blocking and unblocking, invoking {@link #tryAcquire}
     * until success or the thread is interrupted.  This method can be
     * used to implement method {@link Lock#lockInterruptibly}.
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquire} but is otherwise uninterpreted and
     *        can represent anything you like.
     * @throws InterruptedException if the current thread is interrupted
     */
    public final void acquireInterruptibly(int arg) throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (!tryAcquire(arg))
            doAcquireInterruptibly(arg);
    }


AbstractQueuedSynchronizer.doAcquireInterruptibly大体上相当于前面的acquireQueued,关键的区别在于检测到interrupted后的处理,acquireQueued简单的记录下中断曾经发生,然后就象没事人似的去尝试获取锁,失败则休眠。而doAcquireInterruptibly检测到中断则直接退出循环,抛出InterruptedException异常。

AbstractQueuedSynchronizer.doAcquireInterruptibly(int arg)
/**
     * Acquires in exclusive interruptible mode.
     * @param arg the acquire argument
     */
    private void doAcquireInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.EXCLUSIVE);
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    return;
                }
                /*
                acquireQueued代码:
           if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
*/
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    break;
            }
        } catch (RuntimeException ex) {
            cancelAcquire(node);
            throw ex;
        }
        // Arrive here only if interrupted
        // 取消获取锁尝试,将当前节点从等待队列中移除
        cancelAcquire(node);
        throw new InterruptedException();
    }


在抛出异常之前,doAcquireInterruptibly还做了一件事情,cancelAcquire。cancelAcquire中有些细节值得玩味,参见代码中笔者注释。

AbstractQueuedSynchronizer.cancelAcquire(Node node)
/**
     * Cancels an ongoing attempt to acquire.
     *
     * @param node the node
     */
    private void cancelAcquire(Node node) {
    // Ignore if node doesn't exist
        if (node == null)
        return;

    node.thread = null;

    // Skip cancelled predecessors
    // 头节点一定不会是在等待状态,所以不会被cancel,所以这里一定能找到一个节点而不用担心null
    Node pred = node.prev;
    while (pred.waitStatus > 0)
        node.prev = pred = pred.prev;

    // Getting this before setting waitStatus ensures staleness
    Node predNext = pred.next;
    // Can use unconditional write instead of CAS here
    node.waitStatus = Node.CANCELLED;

    // If we are the tail, remove ourselves
    if (node == tail && compareAndSetTail(node, pred)) {
        compareAndSetNext(pred, predNext, null);
    } else {
        // If "active" predecessor found...
        if (pred != head
        && (pred.waitStatus == Node.SIGNAL
            || compareAndSetWaitStatus(pred, 0, Node.SIGNAL))
        && pred.thread != null) {

        // If successor is active, set predecessor's next link
        Node next = node.next;
        if (next != null && next.waitStatus <= 0)
            compareAndSetNext(pred, predNext, next);
        } else {
        /*这里如果不调用unparkSuccessor, 若在interrupted之后,执行到上面一句将waitStatus置CANCELLED之前,锁被释放,该线程被唤醒,则释放锁线程的unparkSuccessor不能起到预期作用,所以这里需要调用unparkSuccessor.即使此时持有锁的线程没有释放锁也不会有严重后果,被unpark的线程在获取锁失败后会继续park*/
        unparkSuccessor(node);
        }
        node.next = node; // help GC
    }
    }
分享到:
评论

相关推荐

    java核心知识点整理.pdf

    可达性分析............................................................................................................................................... 26 2.3.2. 2.3.3. 老年代 ........................

    ReentrantLock源码分析

    ### ReentrantLock源码分析 #### 一、ReentrantLock简介 ReentrantLock是一个基于`AbstractQueuedSynchronizer`(AQS)实现的高级锁工具类。与传统的synchronized关键字相比,ReentrantLock提供了更多控制手段,比如...

    JAVA核心知识点整理(有效)

    可达性分析............................................................................................................................................... 26 2.3.2. 2.3.3. 老年代 ........................

    3.1.4.AQS底层原理分析1

    【3.1.4.AQS底层原理分析1】 在Java并发编程中,AbstractQueuedSynchronizer(AQS)是一个核心的同步组件,用于构建锁和同步器的基础框架。AQS是一个抽象类,它提供了线程同步的基本机制,包括线程的排队、等待和...

    6、JUC并发工具类在大厂的应用场景详解(1).pdf

    - `lockInterruptibly()`: 可中断的获取锁,如果当前线程在等待锁时被中断,则抛出`InterruptedException`。 - `tryLock()`: 尝试获取锁,若获取失败则立即返回`false`,不会使线程进入阻塞状态。 - `tryLock...

    高级Java多线程面试题及回答(合集).docx

    - 可重入性:`ReentrantLock`支持可重入,即线程可以获取同一锁多次。 - 精细化控制:`Lock`提供了更细粒度的锁,如公平锁和非公平锁,读写锁等。 - 可中断:`Lock.lockInterruptibly()`可以让线程在等待锁时响应...

    java死锁问题

    为了更好地理解和解决死锁问题,可以编写模拟死锁的示例代码,通过调试和分析,加深对死锁概念的理解。例如,创建两个线程,每个线程持有一个锁并尝试获取另一个锁,这样就会形成经典的哲学家进餐问题的模型。 总之...

    Java的Lock小结

    这种方式与`synchronized`不同,后者会在代码块结束或抛出异常时自动释放锁。 #### 三、Lock与synchronized的区别 - **锁的管理**:`synchronized`的锁是由JVM自动管理的,因此开发者无需担心锁的释放问题。而`...

Global site tag (gtag.js) - Google Analytics