/*
* 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);
}
}
分享到:
相关推荐
LockSupport是Java中用于多线程同步的一个工具类,它提供了一组基础的线程阻塞和解除阻塞的方法。这个类位于java.util.concurrent.locks包下,是实现并发编程中AQS(AbstractQueuedSynchronizer)框架的重要基础之一...
在Java并发编程领域,Unsafe类和LockSupport类是两个重要的底层工具类,它们提供了低级别的内存操作和线程控制,使得开发者能够实现高效的并发算法和数据结构。本文将深入探讨这两个类的源码,理解它们的工作原理和...
AQS还提供了ConditionObject类,它与AQS一起使用,可以实现更灵活的线程间协作模式。通过ConditionObject可以更细致地控制线程的等待和唤醒,而不仅仅依赖于Object类提供的wait/notify机制。 总结来说,AQS作为Java...
在 Java 中,许多同步类都依赖于 AQS,如 ReentrantLock、Semaphore 和 CountDownLatch 等。ReentrantLock 是一个独占锁,state 初始化为 0,表示未锁定状态。当线程 lock() 时,会调用 tryAcquire() 并将 state+1。...
AQS通过模板方法的设计模式,将一些方法定义为final,这些方法可以被子类直接使用,而将一些可以被子类改写的方法定义为protected,这些方法需要被子类提供具体实现。 AQS中的同步器可以被分为两部分:同步队列和...
Java的锁和同步器框架AbstractQueuedSynchronizer(AQS)就是通过LockSupport的`park()`和`unpark()`方法来管理线程的阻塞和恢复执行。 `park()`方法用于阻塞当前线程,如果当前线程能够获取到许可(即没有其他线程...
在Java并发编程领域,AbstractQueuedSynchronizer(AQS)是一个非常重要的基础组件,它是Java并发包java.util.concurrent中实现锁和同步器的核心工具类。AQS通过维护一个FIFO的等待队列来管理线程的同步状态,它提供...
- 如果当前线程无法获取锁,它将被封装为一个`Node`对象并插入到等待队列中,然后该线程会被挂起等待。 3. **释放锁的过程**:当线程完成其任务后,通过调用`ReentrantLock.unlock()`方法来释放锁。这个过程涉及到...
LockSupport是线程阻塞和唤醒的低级工具,提供了park()和unpark()方法,用于线程的挂起和恢复。它是基于 Unsafe 类实现的,可以实现非阻塞的线程挂起,提高并发效率。 三、Condition接口的设计与实现 Condition接口...
条件队列通常与锁配合使用,它提供了让线程在某个条件下挂起,直到被其他线程通知唤醒的功能。条件队列中的每个节点代表一个等待条件的线程。与同步队列不同,条件队列是以单向链表的形式存在,头尾节点分别称为...
AQS采用模板方法模式,大多数与锁相关的操作都在`AbstractQueuedSynchronizer`类中完成。它提供了一个同步器的框架,其中包含了共享资源的状态管理、线程排队机制等核心功能。开发者可以通过继承AQS并实现其模板方法...
LockSupport是Java并发包中用于线程控制的工具类,提供如`park()`和`unpark(Thread thread)`等方法。这些方法可以用来暂停和恢复线程的执行,是构建复杂并发控制的基础。 **AbstractQueuedSynchronizer (AQS)** ...
Java并发编程中的`JUC`(Java Util Concurrency)库是Java平台中用于处理多线程问题的核心工具包,它提供了一系列高效、线程安全的工具类,帮助开发者编写并发应用程序。`AQS`(AbstractQueuedSynchronizer)是JUC库中的...
AQS是一个抽象类,它提供了线程同步的基本机制,包括线程的排队、等待和唤醒。在Java.util.concurrent包中,许多并发工具类如ReentrantLock、Semaphore、CountDownLatch等都基于AQS实现。 AQS的核心概念是基于一个...
AQS,全称为AbstractQueuedSynchronizer,是一个抽象类,为构建实现阻塞锁和相关同步器(如信号量、事件等)提供了一种基础框架。它内部基于一个FIFO(先进先出)的等待队列来管理线程的同步状态。AQS的设计理念是将...
如果自旋达到一定次数(默认10次,可调整),轻量级锁会升级为重量级锁,此时线程会被挂起,等待被唤醒。 AQS提供了两种基本的同步模式:独占模式和共享模式。独占模式下,只有一个线程可以获取锁,例如`...
8 锁的现象是 Java 中的一种并发编程模型,描述了 8 种不同的锁机制,它们是:公平锁、非公平锁、可重入锁、读写锁、StampedLock、LockSupport、AbstractQueuedSynchronizer(AQS)、ReentrantLock。这些锁机制可以...
`LockSupport`工具类提供了`park()`和`unpark(Thread thread)`方法,用于线程的阻塞和唤醒,这些方法在AQS中起到了关键作用。 总之,显式锁和AQS的出现极大地丰富了Java并发编程的能力,通过定制化同步策略,我们...