本文作为解析AQS文章的第一篇,着重介绍队列元素的Node的实现。
java线程间通信方式
java线程间通信方式,有volatile基于可见内存可见性实现的通信,有管道PipedOutputStream,PipedInputStream 基于内存传递实现的通信,有等待通知机制实现的wait,notify,join等方式;实际等待通知机制也是基于共享内存实现的;这里引入一个管程 monitor 的概念,管程是指管理共享变量以及对共享变量的操作的过程。java关键字 synchronized 就是基于MESA类型管程实现的,而AQS也是基于该种管程实现的。
了解MESA管程模型
管程大概示意图
这里,我们知道管程有一个入口处的同步等待队列,和内部的条件等待队列,且在条件队列上的元素是从队首进入到同步队列的队尾就可以。
源码解读
static final class Node {
// 常量,标志节点是共享模式还是独占模式的
/** Marker to indicate a node is waiting in shared mode */
static final Node SHARED = new Node();
/** Marker to indicate a node is waiting in exclusive mode */
static final Node EXCLUSIVE = null;
// 常量,标识当前节点的状态
/** 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;
// 5个属性,分别是waitStatus,thread,prev,next,nextWaiter
/**
* Status field, taking on only the values:
* SIGNAL: The successor of this node is (or will soon be)
* blocked (via park), so the current node must
* unpark its successor when it releases or
* cancels. To avoid races, acquire methods must
* first indicate they need a signal,
* then retry the atomic acquire, and then,
* on failure, block.
* CANCELLED: This node is cancelled due to timeout or interrupt.
* Nodes never leave this state. In particular,
* a thread with cancelled node never again blocks.
* CONDITION: This node is currently on a condition queue.
* It will not be used as a sync queue node
* until transferred, at which time the status
* will be set to 0. (Use of this value here has
* nothing to do with the other uses of the
* field, but simplifies mechanics.)
* PROPAGATE: A releaseShared should be propagated to other
* nodes. This is set (for head node only) in
* doReleaseShared to ensure propagation
* continues, even if other operations have
* since intervened.
* 0: None of the above
*
* The values are arranged numerically to simplify use.
* Non-negative values mean that a node doesn't need to
* signal. So, most code doesn't need to check for particular
* values, just for sign.
*
* The field is initialized to 0 for normal sync nodes, and
* CONDITION for condition nodes. It is modified using CAS
* (or when possible, unconditional volatile writes).
*/
volatile int waitStatus;
/**
* Link to predecessor node that current node/thread relies on
* for checking waitStatus. Assigned during enqueuing, and nulled
* out (for sake of GC) only upon dequeuing. Also, upon
* cancellation of a predecessor, we short-circuit while
* finding a non-cancelled one, which will always exist
* because the head node is never cancelled: A node becomes
* head only as a result of successful acquire. A
* cancelled thread never succeeds in acquiring, and a thread only
* cancels itself, not any other node.
*/
volatile Node prev;
/**
* Link to the successor node that the current node/thread
* unparks upon release. Assigned during enqueuing, adjusted
* when bypassing cancelled predecessors, and nulled out (for
* sake of GC) when dequeued. The enq operation does not
* assign next field of a predecessor until after attachment,
* so seeing a null next field does not necessarily mean that
* node is at end of queue. However, if a next field appears
* to be null, we can scan prev's from the tail to
* double-check. The next field of cancelled nodes is set to
* point to the node itself instead of null, to make life
* easier for isOnSyncQueue.
*/
volatile Node next;
/**
* The thread that enqueued this node. Initialized on
* construction and nulled out after use.
*/
volatile Thread thread;
/**
* Link to next node waiting on condition, or the special
* 在条件队列上表示连接到下一个节点的引用,或者是表示下一个节点是共享节点。
* value SHARED. Because condition queues are accessed only
* 由于条件队列的访问只能在独占模式下
* when holding in exclusive mode, we just need a simple
* 所以我们只需要一个单向链表
* linked queue to hold nodes while they are waiting on
* 保存等待在条件队列上的元素。
* conditions. They are then transferred to the queue to
* 这些节点之后会被转移到同步队列重新获取资源
* re-acquire. And because conditions can only be exclusive,
* 由于条件只能是独占的,
* we save a field by using special value to indicate shared
* 所以我们使用特殊的值表示共享模式
* mode.
*/
Node nextWaiter;
/**
* Returns true if node is waiting in shared mode.
*/
final boolean isShared() {
return nextWaiter == SHARED;
}
/**
* Returns previous node, or throws NullPointerException if null.
* Use when predecessor cannot be null. The null check could
* be elided, but is present to help the VM.
*
* @return the predecessor of this node
*/
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
// 这个构造器仅在初始化同步队列时有用,用于创建同步队列的头节点,默认的共享变量也是调用该无参构造器实例化的
Node() { // Used to establish initial head or SHARED marker
}
// 同步队列添加元素时使用,使用 nextWaiter 表示该同步队列是共享的还是独占的;意味着等待队列上的初始化状态都是0
Node(Thread thread, Node mode) { // Used by addWaiter
this.nextWaiter = mode;
this.thread = thread;
}
// 条件队列添加元素时使用,使用 waitStatus = -2 ,表示为条件阻塞队列;意味着条件队列上的所有节点的等待状态都是 -2
Node(Thread thread, int waitStatus) { // Used by Condition
this.waitStatus = waitStatus;
this.thread = thread;
}
}
总结
Node 节点有5个属性,对于构造双向链表可以使用 next 与 prev,对于单向链表可以使用nextWaiter;有三种构造器,一种是用来初始化 同步队列,一种是用来在同步队列中添加元素,仅指定了节点是共享的还是独占的,所以节点的状态需要额外的设置;另一种是用来在条件队列中添加元素,指定了所有节点状态都是-2,prev与next 初始化时都是null;