`
Donald_Draper
  • 浏览: 951984 次
社区版块
存档分类
最新评论

AQS线程挂起辅助类LockSupport

    博客分类:
  • JUC
阅读更多
/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent.locks;
import java.util.concurrent.*;
import sun.misc.Unsafe;


/**
 * Basic thread blocking primitives for creating locks and other
 * synchronization classes.
 *
 LockSupport基于线程最原始阻塞,提供锁的创建,服务于其他同步器
 * <p>This class associates, with each thread that uses it, a permit
 * (in the sense of the {@link java.util.concurrent.Semaphore
 * Semaphore} class). A call to {@code park} will return immediately
 * if the permit is available, consuming it in the process; otherwise
 * it <em>may</em> block.  A call to {@code unpark} makes the permit
 * available, if it was not already available. (Unlike with Semaphores
 * though, permits do not accumulate. There is at most one.)
 *
 LockSupport与所有用到它的每一个线程相关联,permit在某种意义上,可以理解为
 信号量java.util.concurrent.Semaphore。
如果permit可以用,park函数会立即返回,则消费permit,否则肯能阻塞。
如果permit没有可利用的,则unpark会使permit可以用。与信号量不同的是,
permits不允许累计,最多只能有一个。


 * <p>Methods {@code park} and {@code unpark} provide efficient
 * means of blocking and unblocking threads that do not encounter the
 * problems that cause the deprecated methods {@code Thread.suspend}
 * and {@code Thread.resume} to be unusable for such purposes: Races
 * between one thread invoking {@code park} and another thread trying
 * to {@code unpark} it will preserve liveness, due to the
 * permit. Additionally, {@code park} will return if the caller's
 * thread was interrupted, and timeout versions are supported. The
 * {@code park} method may also return at any other time, for "no
 * reason", so in general must be invoked within a loop that rechecks
 * conditions upon return. In this sense {@code park} serves as an
 * optimization of a "busy wait" that does not waste as much time
 * spinning, but must be paired with an {@code unpark} to be
 * effective.
 *
park和unpark提供有效分方式blocking and unblocking线程,并且不会遇到Thread.suspend
和Thread.resume方法引起的问题:一个线程park,另一个线程unpark,有由于permit,
线程可能处于liveness(运行)状态。如果当前线程处于中断状态,park会立即返回,
同时支持超时等待park。由于未知的原因,park方法会在任何时候返回,所以必须
循环检查返回的条件。park方法是busy wait的一种优化,不会浪费太多的时间自旋,
park必须与unpark配合使用。

 * <p>The three forms of {@code park} each also support a
 * {@code blocker} object parameter. This object is recorded while
 * the thread is blocked to permit monitoring and diagnostic tools to
 * identify the reasons that threads are blocked. (Such tools may
 * access blockers using method {@link #getBlocker}.) The use of these
 * forms rather than the original forms without this parameter is
 * strongly encouraged. The normal argument to supply as a
 * {@code blocker} within a lock implementation is {@code this}.
 *
 park方法有三种形式,其中一种带Obejct参数的  
 public static void park(Object blocker) 
 。当线程阻塞时,记录线程,以便监控和诊断工具,确定阻塞的原因。
 我们可以用getBlocker方法获取阻塞线程。强烈建议使用带参数的park方法,
 而不是无参数的park方法。待参数的park,阻塞的线程,内部要提供一个lock的实现。


 * <p>These methods are designed to be used as tools for creating
 * higher-level synchronization utilities, and are not in themselves
 * useful for most concurrency control applications. 

 这些方法是为方便创建高质量的同步器,而设计,不是为大多数的并发应用。
 * The {@code park}
 * method is designed for use only in constructions of the form:
 * <pre>while (!canProceed()) { ... LockSupport.park(this); }</pre>
 * where neither {@code canProceed} nor any other actions prior to the
 * call to {@code park} entail locking or blocking.  Because only one
 * permit is associated with each thread, any intermediary uses of
 * {@code park} could interfere with its intended effects.
 *
 这一段就不翻译了,暂时理解的不是很透彻



 * <p><b>Sample Usage.</b> Here is a sketch of a first-in-first-out
 * non-reentrant lock class:
 这是一个基于FIFO队列的非重入锁的实现
 * <pre>{@code
 * class FIFOMutex {
 *   private final AtomicBoolean locked = new AtomicBoolean(false); //原子锁
 *   private final Queue<Thread> waiters//线程等待队列
 *     = new ConcurrentLinkedQueue<Thread>();
 *   //加锁
 *   public void lock() {
 *     boolean wasInterrupted = false;
       //获取当前线程加入到,线程等待队列
 *     Thread current = Thread.currentThread();
 *     waiters.add(current);
 *
 *     // Block while not first in queue or cannot acquire lock
       //当前线程,不是队列的头部,并且获取锁失败,则park当前线程
 *     while (waiters.peek() != current ||
 *            !locked.compareAndSet(false, true)) {
 *        LockSupport.park(this);
          //如果线程处于中断状态,则wasInterrupted为true
 *        if (Thread.interrupted()) // ignore interrupts while waiting
 *          wasInterrupted = true;
 *     }
 *     //如果是队列的头部,且获取锁成功,从队列中移除,当前线程
 *     waiters.remove();
 *     if (wasInterrupted)          // reassert interrupt status on exit
 *        current.interrupt();
 *   }
 *   //解锁
 *   public void unlock() {
 *     locked.set(false);//设置锁为打开状态
 *     LockSupport.unpark(waiters.peek());//unpark队列头部线程
 *   }
 * }}</pre>
 */

public class LockSupport {
    //LockSupport不支持,实例化,我们可以通过,调用其方法实现相关功能。
    private LockSupport() {} // Cannot be instantiated.

    // Hotspot implementation via intrinsics API
    //Hotspot VM调用操作系统API的辅助工具
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long parkBlockerOffset;

    static {
        try {
            parkBlockerOffset = unsafe.objectFieldOffset
                (java.lang.Thread.class.getDeclaredField("parkBlocker"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    private static void setBlocker(Thread t, Object arg) {
        // Even though volatile, hotspot doesn't need a write barrier here.
	//即使是volatile,在这里方法调用,hotspot VM 也不需要一个writer barrier
        unsafe.putObject(t, parkBlockerOffset, arg);
    }

    /**
     * Makes available the permit for the given thread, if it
     * was not already available.  If the thread was blocked on
     * {@code park} then it will unblock.  Otherwise, its next call
     * to {@code park} is guaranteed not to block. This operation
     * is not guaranteed to have any effect at all if the given
     * thread has not been started.
     *
     * @param thread the thread to unpark, or {@code null}, in which case
     *        this operation has no effect
     */
     //当permit不可用时,unpark方法可以使permit对指定线程可用。
     //如果线程被阻塞时,调用此方法,可以unblock,或者说,下次调用park时,
     //保证线程不会被阻塞。当指定线程没有启动,则unpark没有作用。
    public static void unpark(Thread thread) {
        if (thread != null)
            unsafe.unpark(thread);
    }

    /**
     * Disables the current thread for thread scheduling purposes unless the
     * permit is available.
     *使当前线程不能被调度,除非permit可用
     * <p>If the permit is available then it is consumed and the call returns
     * immediately; otherwise
     * the current thread becomes disabled for thread scheduling
     * purposes and lies dormant until one of three things happens:
     *如果permit可用,则消费掉,并立刻返回;
     否则使当前线程不能被调度,处于睡眠状态,直到下面3个条件发生。
     * <ul>
     * <li>Some other thread invokes {@link #unpark unpark} with the
     * current thread as the target; or
     *其他线程unpark当前线程
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread; or
     *其他线程中断当前线程
     * <li>The call spuriously (that is, for no reason) returns.
     * </ul>
     *park方法由于未知原因返回
     * <p>This method does <em>not</em> report which of these caused the
     * method to return. Callers should re-check the conditions which caused
     * the thread to park in the first place. Callers may also determine,
     * for example, the interrupt status of the thread upon return.
     *这个方法不会报告什么原因引起return。调用者应该重新检查线程,在第一次被
     park的条件。调用者也可以根据返回,来判断线程的中断状态。
     * @param blocker the synchronization object responsible for this
     *        thread parking
     * @since 1.6
     */
    public static void park(Object blocker) {
        Thread t = Thread.currentThread();
        setBlocker(t, blocker);
        unsafe.park(false, 0L);
        setBlocker(t, null);
    }

    /**
     * Disables the current thread for thread scheduling purposes, for up to
     * the specified waiting time, unless the permit is available.
     *此方法与park(Object blocker)类似,只不过要延迟long nanos,才park线程
     * <p>If the permit is available then it is consumed and the call
     * returns immediately; otherwise the current thread becomes disabled
     * for thread scheduling purposes and lies dormant until one of four
     * things happens:
     *
     * <ul>
     * <li>Some other thread invokes {@link #unpark unpark} with the
     * current thread as the target; or
     *
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread; or
     *
     * <li>The specified waiting time elapses; or
     *
     * <li>The call spuriously (that is, for no reason) returns.
     * </ul>
     *
     * <p>This method does <em>not</em> report which of these caused the
     * method to return. Callers should re-check the conditions which caused
     * the thread to park in the first place. Callers may also determine,
     * for example, the interrupt status of the thread, or the elapsed time
     * upon return.
     *
     * @param blocker the synchronization object responsible for this
     *        thread parking
     * @param nanos the maximum number of nanoseconds to wait
     * @since 1.6
     */调用者也可以根据返回,来判断线程的中断状态,或等时间耗完,直接返回。
    public static void parkNanos(Object blocker, long nanos) {
        if (nanos > 0) {
            Thread t = Thread.currentThread();
            setBlocker(t, blocker);
            unsafe.park(false, nanos);
            setBlocker(t, null);
        }
    }

    /**
     * Disables the current thread for thread scheduling purposes, until
     * the specified deadline, unless the permit is available.
     * 与上述方法类似,不同的是有一个deadline
     * <p>If the permit is available then it is consumed and the call
     * returns immediately; otherwise the current thread becomes disabled
     * for thread scheduling purposes and lies dormant until one of four
     * things happens:
     *
     * <ul>
     * <li>Some other thread invokes {@link #unpark unpark} with the
     * current thread as the target; or
     *
     * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
     * current thread; or
     *
     * <li>The specified deadline passes; or
     *
     * <li>The call spuriously (that is, for no reason) returns.
     * </ul>
     *
     * <p>This method does <em>not</em> report which of these caused the
     * method to return. Callers should re-check the conditions which caused
     * the thread to park in the first place. Callers may also determine,
     * for example, the interrupt status of the thread, or the current time
     * upon return.
     *
     * @param blocker the synchronization object responsible for this
     *        thread parking
     * @param deadline the absolute time, in milliseconds from the Epoch,
     *        to wait until
     * @since 1.6
     */
    public static void parkUntil(Object blocker, long deadline) {
        Thread t = Thread.currentThread();
        setBlocker(t, blocker);
        unsafe.park(true, deadline);
        setBlocker(t, null);
    }

    /**
     * Returns the blocker object supplied to the most recent
     * invocation of a park method that has not yet unblocked, or null
     * if not blocked.  The value returned is just a momentary
     * snapshot -- the thread may have since unblocked or blocked on a
     * different blocker object.
     *返回最近调用park方法,还没有阻塞的线程。返回值是一个瞬间的快照
     * @param t the thread
     * @return the blocker
     * @throws NullPointerException if argument is null
     * @since 1.6
     */
    public static Object getBlocker(Thread t) {
        if (t == null)
            throw new NullPointerException();
        return unsafe.getObjectVolatile(t, parkBlockerOffset);
    }

    /**
     * Disables the current thread for thread scheduling purposes unless the
     * permit is available.
     *与上述方法类型
     * <p>If the permit is available then it is consumed and the call
     * returns immediately; otherwise the current thread becomes disabled
     * for thread scheduling purposes and lies dormant until one of three
     * things happens:
     *
     * <ul>
     *
     * <li>Some other thread invokes {@link #unpark unpark} with the
     * current thread as the target; or
     *
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread; or
     *
     * <li>The call spuriously (that is, for no reason) returns.
     * </ul>
     *
     * <p>This method does <em>not</em> report which of these caused the
     * method to return. Callers should re-check the conditions which caused
     * the thread to park in the first place. Callers may also determine,
     * for example, the interrupt status of the thread upon return.
     */
    public static void park() {
        unsafe.park(false, 0L);
    }

    /**
     * Disables the current thread for thread scheduling purposes, for up to
     * the specified waiting time, unless the permit is available.
     *
     * <p>If the permit is available then it is consumed and the call
     * returns immediately; otherwise the current thread becomes disabled
     * for thread scheduling purposes and lies dormant until one of four
     * things happens:
     *
     * <ul>
     * <li>Some other thread invokes {@link #unpark unpark} with the
     * current thread as the target; or
     *
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread; or
     *
     * <li>The specified waiting time elapses; or
     *
     * <li>The call spuriously (that is, for no reason) returns.
     * </ul>
     *
     * <p>This method does <em>not</em> report which of these caused the
     * method to return. Callers should re-check the conditions which caused
     * the thread to park in the first place. Callers may also determine,
     * for example, the interrupt status of the thread, or the elapsed time
     * upon return.
     *等待一段时间park
     * @param nanos the maximum number of nanoseconds to wait
     */
    public static void parkNanos(long nanos) {
        if (nanos > 0)
            unsafe.park(false, nanos);
    }

    /**
     * Disables the current thread for thread scheduling purposes, until
     * the specified deadline, unless the permit is available.
     *
     * <p>If the permit is available then it is consumed and the call
     * returns immediately; otherwise the current thread becomes disabled
     * for thread scheduling purposes and lies dormant until one of four
     * things happens:
     *
     * <ul>
     * <li>Some other thread invokes {@link #unpark unpark} with the
     * current thread as the target; or
     *
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread; or
     *
     * <li>The specified deadline passes; or
     *
     * <li>The call spuriously (that is, for no reason) returns.
     * </ul>
     *
     * <p>This method does <em>not</em> report which of these caused the
     * method to return. Callers should re-check the conditions which caused
     * the thread to park in the first place. Callers may also determine,
     * for example, the interrupt status of the thread, or the current time
     * upon return.
     *park到指定的时间deadline,除非permit可用,unpark可使permit可用
     * @param deadline the absolute time, in milliseconds from the Epoch,
     *        to wait until
     */
    public static void parkUntil(long deadline) {
        unsafe.park(true, deadline);
    }
}
分享到:
评论

相关推荐

    面试必问之AQS原理详解.pdf

    简单来说 AQS 会把所有的请求线程构成一个 CLH 队列,当一个线程执行完毕 (lock.unlock())时会激活自己的后继节点,但正在执行的线程并不在队列中, 而那些等待执行的线程全部处于阻塞状态,经过调查线程的显式...

    Java中LockSupport的使用.docx

    java锁和同步器框架的核心 AQS: AbstractQueuedSynchronizer,就是通过调用 LockSupport .park()和 LockSupport .unpark()实现线程的阻塞和唤醒 的。 LockSupport 很类似于二元信号量(只有1个许可证可供使用),如果...

    java并发编程:juc、aqs

    Java 并发编程中的 JUC(java.util.concurrent)库以及其核心组件 AQS(AbstractQueuedSynchronizer)在构建高性能、可伸缩性的多线程应用方面具有重要的地位。 AQS 是 JUC 中的核心组件,它提供了一个框架,让...

    Java 多线程与并发(10-26)-JUC锁- 锁核心类AQS详解.pdf

    Java 多线程与并发(10_26)-JUC锁_ 锁核心类AQS详解

    aqs_demo.rar

    aqs同步器&redisson锁

    【2018最新最详细】并发多线程教程

    【2018最新最详细】并发多线程教程,课程结构如下 1.并发编程的优缺点 2.线程的状态转换以及基本操作 3.java内存模型以及happens-before规则 4.彻底理解synchronized 5.彻底理解volatile 6.你以为你真的了解final吗...

    AQS流程图.html

    java锁AQS基础逻辑

    Java并发之AQS详解.pdf

    Java并发之AQS详解.pdf

    Java volatile与AQS锁内存可见性

    从JUC中的AQS引入,讲解Java volatile与AQS锁内存可见性

    最新AQS资料整理.pdf

    最新AQS资料整理,里面知识涉及到AQS所遇到的所有问题,还有视频可以观看,可以帮助大家解惑,可以轻松应对职场问题

    juc aqs java

    juc 的aqs介绍。

    AQS流程图ReentranLock.vsdx

    AQS流程图ReentranLock.vsdx

    java面试题_多线程(68题).pdf

    1. 什么是线程? 2. 什么是线程安全和线程不安全? 3. 什么是⾃旋锁? 4. 什么是CAS? 5. 什么是乐观锁和悲观锁? 6. 什么是AQS? 7. 什么是原⼦操作?在Java Concurrency API中有哪些原⼦类(atomic classes)? 8. ...

    JDK_AQS解析

    解析AbstractQueuedSynchronizer这个类中,锁的获取、释放的相关逻辑。

    并发锁核心类AQS学习笔记

    JUC 包中的同步类基本都是基于 AQS 同步器来实现的,如 ReentrantLock,Semaphore 等。 二、原理 1、AQS 工作机制: 如果被请求的共享资源空闲,则将当前请求资源的线程设置为有效的工作线程,并且将共享资源设置为...

    AQS源码分析 (1).pdf

    java锁底层实现,AQS源码分析。我在公司内部分享写的,如果想进一步了解,可以私聊

    JUC核心类AQS的底层原理

    详细阐述了ReentrantLock通过AQS获取锁到释放锁的过程,附有关键方法的源码及注释

    AQS抽象队列同步器,AQS抽象队列同步器

    AQS抽象队列同步器,AQS抽象队列同步器

    Java AQS详解.docx

    谈到并发,不得不谈ReentrantLock;...类如其名,抽象的队列式的同步器,AQS定义了一套多线程访问共享资源的同步器框架,许多同步类实现都依赖于它,如常用的ReentrantLock/Semaphore/CountDownLatch...。

Global site tag (gtag.js) - Google Analytics