问题
本文通过源码阐述两个问题
- WaitNode是干嘛的
- 为什么JDK1.7中FutureTask放弃了使用了AQS
其他源码请查看其他Blog
WaitNode
Treiber stack
Treiber Stack在 R. Kent Treiber在1986年的论文Systems Programming: Coping with Parallelism中首次出现。它是一种无锁并发栈,其无锁的特性是基于CAS原子操作实现的。
下面给出的Java语言实现为《Java并发编程实战》一书的15.4.1小结中的实现。Treiber Stack的实现套路很简单,就是CAS+重试,不需要任何注释就能轻松的看懂代码。
public class TreiberStack<E> {
AtomicReference<Node<E>> top = new AtomicReference<>();
/**
* 入栈
* @param item E
*/
public void push(E item) {
Node<E> newHead = new Node<E>(item);
Node<E> oldHead;
//使用CAS操作循环设置栈头,保证在多线程情况下push新节点时新节点是正确的栈头
do {
oldHead = top.get();
newHead.next = oldHead;
//如果在循环中oldHead没有变化,即oldHead值为期望值,则更新
} while (!top.compareAndSet(oldHead, newHead));
}
/**
* 出栈
* @return E
*/
public E pop() {
Node<E> oldHead;
Node<E> newHead;
//使用CAS操作循环设置栈头,保证在多线程情况下pop的时候取到的是最头的节点
do {
oldHead = top.get();
if (oldHead == null) {
return null;
}
newHead = oldHead.next;
} while (!top.compareAndSet(oldHead, newHead));
return oldHead.item;
}
private static class Node<E> {
final E item;
Node<E> next;
Node(E item) {
this.item = item;
}
}
}
WaitNode是干嘛的
/*Treiber椎,用于保存由于调用Future.get方法而阻塞的线程*/
private volatile WaitNode waiters;
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
每当一个线程调用Future.get去获取任务的执行结果时,如果当前任务还没有执行结束、还没有被取消或者执行中未抛出异常。将产生一个新的WaitNode类型的节点,该节点持有调用Future.get方法的线程的引用,放入到Treiber stack中。FutureTask成员变量waiters更新为最新的WaitNode节点。如下图。
为什么放弃了使用了AQS
源码注释:
/*
* Revision notes: This differs from previous versions of this
* class that relied on AbstractQueuedSynchronizer, mainly to
* avoid surprising users about retaining interrupt status during
* cancellation races. Sync control in the current design relies
* on a "state" field updated via CAS to track completion, along
* with a simple Treiber stack to hold waiting threads.
*
* Style note: As usual, we bypass overhead of using
* AtomicXFieldUpdaters and instead directly use Unsafe intrinsics.
*/
从Java1.7开始Doug Lea对FutureTask进行了重写,不使用AQS去维护WaitNode,而改用上文提到的Treiber Stack,即通过CAS来维护内部的竞争状态,当然也包括了waiters(队头)的状态。 这么做主要是为了在需要竞争时保留中断状态。
Reference
- https://www.cnblogs.com/micrari/p/7719408.html
- https://blog.csdn.net/u011236357/article/details/78339410?locationNum=5&fps=1
- https://zhuanlan.zhihu.com/p/40047276
- https://www.zhihu.com/question/60123950