AQS线程挂起辅助类LockSupport

/*
* 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);
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值