SynchronousQueue 通常被称为无界队列,队列中不存储具体的元素,一个插入操作的完成必须建立在另一个线程的删除操作上。正如官方注释中所说,它看起来更像一个通道。
1. offer()
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
if (e == null) throw new NullPointerException();
// transferer 有两种实现,公平的 TransferQueue 和非公平的 TransferStack,默认是非公平
if (transferer.transfer(e, true, unit.toNanos(timeout)) != null)
return true;
if (!Thread.interrupted())
return false;
// 响应中断
throw new InterruptedException();
}
transfer()
E transfer(E e, boolean timed, long nanos) {
/*
* Basic algorithm is to loop trying one of three actions:
*
* 1. If apparently empty or already containing nodes of same
* mode, try to push node on stack and wait for a match,
* returning it, or null if cancelled.
*
* 2. If apparently containing node of complementary mode,
* try to push a fulfilling node on to stack, match
* with corresponding waiting node, pop both from
* stack, and return matched item. The matching or
* unlinking might not actually be necessary because of
* other threads performing action 3:
*
* 3. If top of stack already holds another fulfilling node,
* help it out by doing its match and/or pop
* operations, and then continue. The code for helping
* is essentially the same as for fulfilling, except
* that it doesn't return the item.
*/
SNode s = null; // constructed/reused as needed
// take() 和 poll() 方法最终都会调用 transfer() 方法,
// 不同在于前者传入的 e 不为空,后者传入的为空,
// 因此这里的 REQUEST 代表的是 poll 操作,DATA 代表的是 take 操作。
int mode = (e == null) ? REQUEST : DATA;
for (;;) {
SNode h = head;
// 头节点为空,或者当前操作和头节点对应的操作相同
if (h == null || h.mode == mode) { // empty or same-mode
// 如果是不等待,不管是头节点为空,还是当前操作和头节点对应的操作相同,都可以直接返回 null,
// 头节点为空说明当前没有不同操作的线程在等待;和头节点操作相同,也说明当前没有不同操作的线程在等待。
if (timed && nanos <= 0) { // can't wait
// 自旋将所有 cancelled 的节点移除,移除完毕返回 null
if (h != null && h.isCancelled())
casHead(h, h.next); // pop cancelled node
else
return null;
}
// CAS 的方式将当前元素构造成的节点设置为新的头节点,
else if (casHead(h, s = snode(s, e, h, mode))) {
SNode m = awaitFulfill(s, timed, nanos);
// awaitFulfill() 方法返回的是 s 的 match 节点,当节点被取消时,match 就是 s 自己
if (m == s) { // wait was cancelled
// 移除 s 并返回 null
clean(s);
return null;
}
// 头节点不为空,当前节点为头节点的 next 节点,说明当前节点是被新入栈的头节点匹配上的,
// 这里将两者出栈,本应该是在头节点线程中完成的,因此作者给出了注释:help s's fulfiller
if ((h = head) != null && h.next == s)
casHead(h, s.next); // help s's fulfiller
return (E) ((mode == REQUEST) ? m.item : s.item);
}
}
// 头节点不为空,且当前操作与头节点的操作不同,进一步判断头节点是否已被匹配,
// 如果还没有未被匹配,则将当前节点进行与之匹配
else if (!isFulfilling(h.mode)) { // try to fulfill
// 进一步判断头节点是否被已取消,是则移除
if (h.isCancelled()) // already cancelled
casHead(h, h.next); // pop and retry
// 可以确定当前操作与头节点匹配,因此构造时直接将其 mode 设置成 FULFILLING
else if (casHead(h, s=snode(s, e, h, FULFILLING|mode))) {
for (;;) { // loop until matched or waiters disappear
SNode m = s.next; // m is s's match
// 当后面的节点由于超时被清除出队列时,会出现 m == null 成立,
// 这时需要将已构造的当前节点清空,因为已经过时
if (m == null) { // all waiters are gone
casHead(s, null); // pop fulfill node
s = null; // use new node next time
break; // restart main loop
}
SNode mn = m.next;
// 将 m 节点的 match 节点通过 CAS 的方式设置成当前节点,设置成功唤醒 m 节点对应的线程
if (m.tryMatch(s)) {
casHead(s, mn); // pop both s and m
return (E) ((mode == REQUEST) ? m.item : s.item);
} else // lost match
// tryMatch() 失败,将重置当前节点的 next 节点
s.casNext(m, mn); // help unlink
}
}
}
// 如果头节点已处于 FULFILLING 状态,帮助其进行相应处理
else { // help a fulfiller
SNode m = h.next; // m is h's match
if (m == null) // waiter is gone
casHead(h, null); // pop fulfilling node
else {
SNode mn = m.next;
if (m.tryMatch(h)) // help match
casHead(h, mn); // pop both h and m
else // lost match
h.casNext(m, mn); // help unlink
}
}
}
}
awaitFulfill()
SNode awaitFulfill(SNode s, boolean timed, long nanos) {
/*
* When a node/thread is about to block, it sets its waiter
* field and then rechecks state at least one more time
* before actually parking, thus covering race vs
* fulfiller noticing that waiter is non-null so should be
* woken.
*
* When invoked by nodes that appear at the point of call
* to be at the head of the stack, calls to park are
* preceded by spins to avoid blocking when producers and
* consumers are arriving very close in time. This can
* happen enough to bother only on multiprocessors.
*
* The order of checks for returning out of main loop
* reflects fact that interrupts have precedence over
* normal returns, which have precedence over
* timeouts. (So, on timeout, one last check for match is
* done before giving up.) Except that calls from untimed
* SynchronousQueue.{poll/offer} don't check interrupts
* and don't wait at all, so are trapped in transfer
* method rather than calling awaitFulfill.
*/
final long deadline = timed ? System.nanoTime() + nanos : 0L;
Thread w = Thread.currentThread();
// shouldSpin() 返回 true 的条件:h == s || h == null || isFulfilling(h.mode)
// 即:当前节点为 head 节点(栈顶),或者栈顶为空,或者节点的 mode 为 FULFILLING
int spins = (shouldSpin(s) ?
(timed ? maxTimedSpins : maxUntimedSpins) : 0);
for (;;) {
// 如果线程被中断过,尝试将节点取消:节点的 match 设置成节点自己
if (w.isInterrupted())
s.tryCancel();
// 当线程挂起后,被唤醒时,它的 match 节点已经被成功设置
SNode m = s.match;
if (m != null)
return m;
// 判断超时
if (timed) {
nanos = deadline - System.nanoTime();
// 已经超时,取消,下轮循环会返回
if (nanos <= 0L) {
s.tryCancel();
continue;
}
}
// 再次判断是否需要继续自旋,需要则将自选次数自减,不需要则下轮循环会挂起线程(不需要判断超时或者超时纳秒数小于 1000 )或者继续自旋
if (spins > 0)
spins = shouldSpin(s) ? (spins-1) : 0;
// 自旋结束,接下来需要挂起线程
else if (s.waiter == null)
s.waiter = w; // establish waiter so can park next iter
else if (!timed)
LockSupport.park(this);
// 如果超时时间设置的小于 1000 纳秒,不进行线程的挂起,而是自旋
else if (nanos > spinForTimeoutThreshold)
LockSupport.parkNanos(this, nanos);
}
}
clean()
void clean(SNode s) {
s.item = null; // forget item
s.waiter = null; // forget thread
/*
* At worst we may need to traverse entire stack to unlink
* s. If there are multiple concurrent calls to clean, we
* might not see s if another thread has already removed
* it. But we can stop when we see any node known to
* follow s. We use s.next unless it too is cancelled, in
* which case we try the node one past. We don't check any
* further because we don't want to doubly traverse just to
* find sentinel.
*/
// 将 s 从栈中移除
SNode past = s.next;
if (past != null && past.isCancelled())
past = past.next;
// Absorb cancelled nodes at head
// 从栈顶开始,把已被取消的节点出栈
SNode p;
while ((p = head) != null && p != past && p.isCancelled())
casHead(p, p.next);
// Unsplice embedded nodes
// 将已被取消的节点出栈,只遍历到 s 处
while (p != null && p != past) {
SNode n = p.next;
if (n != null && n.isCancelled())
p.casNext(n, n.next);
else
p = n;
}
}
tryMatch()
boolean tryMatch(SNode s) {
// 设置节点的 match 节点,并唤醒节点对应的线程
if (match == null &&
UNSAFE.compareAndSwapObject(this, matchOffset, null, s)) {
Thread w = waiter;
if (w != null) { // waiters need at most one unpark
waiter = null;
LockSupport.unpark(w);
}
return true;
}
return match == s;
}
2. poll()
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
E e = transferer.transfer(null, true, unit.toNanos(timeout));
if (e != null || !Thread.interrupted())
return e;
throw new InterruptedException();
}
3. 工作流程
- 此时线程 A 进行 poll 操作,且超时时间为 1 秒,线程 A 进行一定次数的自旋,会将 waiter 设置成当前线程并挂起
- 在线程 A 进行 poll 操作超时之前,线程 B 也进行 poll 操作,且超时时间也为 1 秒
- 此时线程 A 的 poll 操作超时
- 在线程 B 超时前,线程 C 进行 offer 操作,超时时间为 1 秒,但是在 node3 构造完成后,线程 B 刚好超时了
- 在线程 C 超时前,线程 D 进行 poll 操作, poll 操作成功前线程 E 也进行 poll 操作