基于open jdk 11

Flow 、SubmissionPubliser类是 java9中新增的类,都被放在JUC包中

Flow

定义了一种生产者和消费者(订阅者)模型的接口,可以用于流式控制中

Publisher

  1. //流式接口
  2. //定义生产者
  3. @FunctionalInterface
  4. public static interface Publisher<T> {
  5. /**
  6. * 增加订阅者
  7. *
  8. * @param subscriber 订阅者
  9. * @throws NullPointerException if subscriber is null
  10. */
  11. public void subscribe(Subscriber<? super T> subscriber);
  12. }

Subscriber

  1. //订阅者
  2. public static interface Subscriber<T> {
  3. /**
  4. * 在Publisher接收一个新的订阅者时,会调用该方法
  5. *
  6. * @param subscription 订阅包,提供了获取下一个元素和取消获取操作的方法
  7. */
  8. public void onSubscribe(Subscription subscription);
  9. /**
  10. * 获取一个新元素,每次有新元素的时候会被调用
  11. *
  12. * @param item the item
  13. */
  14. public void onNext(T item);
  15. /**
  16. * 发送异常时会被调用
  17. *
  18. * @param throwable the exception
  19. */
  20. public void onError(Throwable throwable);
  21. /**
  22. * 当数据接收完成后调用
  23. */
  24. public void onComplete();
  25. }

Subscription

  1. //订阅包
  2. public static interface Subscription {
  3. /**
  4. * 发起请求,获取元素
  5. *
  6. * @param n 获取的增量,Long.MAX_VALUE表示无限的
  7. */
  8. public void request(long n);
  9. /**
  10. * 取消消息接收
  11. */
  12. public void cancel();
  13. }

Processor

  1. //既可以充当生产者,也可以充当订阅者
  2. public static interface Processor<T,R> extends Subscriber<T>, Publisher<R> {
  3. }
  4. static final int DEFAULT_BUFFER_SIZE = 256;
  5. /**
  6. * 定义的默认缓存区,256
  7. *
  8. * @return the buffer size value
  9. */
  10. public static int defaultBufferSize() {
  11. return DEFAULT_BUFFER_SIZE;
  12. }

SubmissionPublisher

FLow 类的一种实现,可以在并发环境下使用

JDK中的说明:

SubmissionPublisher提供了使用Executor的构造函数,如果生产者是在独立线程中运行,并且能估计消费者数量,就使用Executors.newFixedThreadPool(int)固定线程数量的线程池,否则使用默认,ForkJoinPool.commonPool()

SubmissionPublisher提供缓冲功能,能够使生产者和消费者以不同的速率运行,每个消费者独立使用一个缓冲区,缓冲区在首次使用的时候创建,提供了一个默认值256,并会根据需要扩大到最大值,容量通常扩大到最近的2的次幂或者支持的最大值

SubmissionPublisher可以在多个线程之间共享,会在发布项目之前执行操作或者会发出一个happen-before信号给每个对应的消费者

发布方法支持设置在缓冲区满时如何处理的不同策略,submit(Object)方法会阻塞直到有可用资源,这种用法最简单,但速度慢;offer方法虽然会丢弃项目,但提供了插入动作重试的机会

如果任何Subscriber方法抛出异常,在其订阅将被取消

方法consume(Consumer)简化了对常见情况的支持,其中订阅者的唯一操作是使用supplied的函数请求和处理所有项目

此类还可以作为生成元素的子类的基类,并使用此类中的方法发布。例如,下面是一个周期性发布supplier生成元素的类。 (实际上,您可以添加独立启动和停止生成的方法,在发布者之间共享Executor等,或者使用SubmissionPublisher作为组件而不是超类。)

  1. class PeriodicPublisher<T> extends SubmissionPublisher<T> {
  2. final ScheduledFuture<?> periodicTask;
  3. final ScheduledExecutorService scheduler;
  4. PeriodicPublisher(Executor executor, int maxBufferCapacity,
  5. Supplier<? extends T> supplier,
  6. long period, TimeUnit unit) {
  7. super(executor, maxBufferCapacity);
  8. scheduler = new ScheduledThreadPoolExecutor(1);
  9. periodicTask = scheduler.scheduleAtFixedRate(
  10. () -> submit(supplier.get()), 0, period, unit);
  11. }
  12. public void close() {
  13. periodicTask.cancel(false);
  14. scheduler.shutdown();
  15. super.close();
  16. }
  17. }

以下是Flow.Processor实现的示例,为了简化说明,使用单步向publisher发起请求,更合适的版本可以使用submit方法或者其他实用方法来监控流量

  1. class TransformProcessor<S,T> extends SubmissionPublisher<T>
  2. implements Flow.Processor<S,T> {
  3. final Function<? super S, ? extends T> function;
  4. Flow.Subscription subscription;
  5. TransformProcessor(Executor executor, int maxBufferCapacity,
  6. Function<? super S, ? extends T> function) {
  7. super(executor, maxBufferCapacity);
  8. this.function = function;
  9. }
  10. public void onSubscribe(Flow.Subscription subscription) {
  11. (this.subscription = subscription).request(1);
  12. }
  13. public void onNext(S item) {
  14. subscription.request(1);
  15. submit(function.apply(item));
  16. }
  17. public void onError(Throwable ex) { closeExceptionally(ex); }
  18. public void onComplete() { close(); }
  19. }

使用示例

  1. @Test
  2. public void test1() throws Exception {
  3. SubmissionPublisher<Integer> submissionPublisher = new SubmissionPublisher<>();
  4. submissionPublisher.consume(System.out::println);
  5. submissionPublisher.submit(1);
  6. submissionPublisher.submit(2);
  7. submissionPublisher.offer(3, (x, y) -> {
  8. System.out.println("xxx");
  9. return false;
  10. });
  11. }

使用二进制来表示状态码可以参考:https://blog.csdn.net/qq_36631014/article/details/79675924

基本属性

  1. //缓存区最大值,1073741824
  2. static final int BUFFER_CAPACITY_LIMIT = 1 << 30;
  3. //初始的最大缓存区,缓存区大小必须是2的幂次
  4. static final int INITIAL_CAPACITY = 32;
  5. /**
  6. * BufferedSubscription通过next字段维护了一个链表,这种结构对循环发布非常有用
  7. * 需要遍历O(n)次来检查重复的消费者,但是预计消费比发布少的多
  8. * 取消订阅只发生在遍历循环期间,如果BufferedSubscription方法返回负值表示他们已经关闭
  9. * 为了减少head-of-line阻塞,submit和offer方法首先调用BufferedSubscription的offer方法
  10. * 在满的时候提供了重试
  11. */
  12. BufferedSubscription<T> clients;
  13. /** 运行状态,只在锁内更新*/
  14. volatile boolean closed;
  15. /** 在第一次调用subscribe的时候,设置为true,初始化消费的所有者线程*/
  16. boolean subscribed;
  17. /** 第一次调用subscribe的线程,如果线程曾经改变过,则为null */
  18. Thread owner;
  19. /** 如果不为null,说明在closeExceptionally中生成了异常 */
  20. volatile Throwable closedException;
  21. // 用于构造BufferedSubscriptions的参数
  22. final Executor executor;
  23. //onNext中发生异常时的处理函数
  24. final BiConsumer<? super Subscriber<? super T>, ? super Throwable> onNextHandler;
  25. //表示缓冲区最大容量
  26. final int maxBufferCapacity;

构造函数

  1. //默认构造函数,默认使用ForkJoinPool的公共线程池异步运行subscriber,除非并发级别不支持,则使用普通的线程池
  2. //ThreadPerTaskExecutor
  3. //subscriber的最大缓冲区为256
  4. //Subscriber的异常处理器为null
  5. public SubmissionPublisher() {
  6. this(ASYNC_POOL, Flow.defaultBufferSize(), null);
  7. }
  8. //使用指定的线程池,指定的缓冲区容量创建
  9. public SubmissionPublisher(Executor executor, int maxBufferCapacity) {
  10. this(executor, maxBufferCapacity, null);
  11. }
  12. public SubmissionPublisher(Executor executor, int maxBufferCapacity,
  13. BiConsumer<? super Subscriber<? super T>, ? super Throwable> handler) {
  14. if (executor == null)
  15. throw new NullPointerException();
  16. if (maxBufferCapacity <= 0)
  17. throw new IllegalArgumentException("capacity must be positive");
  18. this.executor = executor;
  19. this.onNextHandler = handler;
  20. //最大容量为离2的幂次最近的值,跟hashMap的计算最大容量算法一样
  21. this.maxBufferCapacity = roundCapacity(maxBufferCapacity);
  22. }

内部类

ConsumerSubscriber

  1. /** 订阅者,供内部使用*/
  2. static final class ConsumerSubscriber<T> implements Subscriber<T> {
  3. final CompletableFuture<Void> status;
  4. final Consumer<? super T> consumer;
  5. Subscription subscription;
  6. ConsumerSubscriber(CompletableFuture<Void> status,
  7. Consumer<? super T> consumer) {
  8. this.status = status; this.consumer = consumer;
  9. }
  10. public final void onSubscribe(Subscription subscription) {
  11. this.subscription = subscription;
  12. //如果元素已经消费完成,那么取消订阅
  13. status.whenComplete((v, e) -> subscription.cancel());
  14. //没有完成继续请求
  15. if (!status.isDone())
  16. subscription.request(Long.MAX_VALUE);
  17. }
  18. //发送错误时候的处理
  19. public final void onError(Throwable ex) {
  20. status.completeExceptionally(ex);
  21. }
  22. //元素消费完成时候的处理
  23. public final void onComplete() {
  24. status.complete(null);
  25. }
  26. //有新元素的时候会被调用
  27. public final void onNext(T item) {
  28. try {
  29. //执行Consumer函数
  30. consumer.accept(item);
  31. } catch (Throwable ex) {
  32. subscription.cancel();
  33. status.completeExceptionally(ex);
  34. }
  35. }
  36. }

ConsumerTask

  1. //订阅者的消费任务
  2. static final class ConsumerTask<T> extends ForkJoinTask<Void>
  3. implements Runnable, CompletableFuture.AsynchronousCompletionTask {
  4. final BufferedSubscription<T> consumer;
  5. ConsumerTask(BufferedSubscription<T> consumer) {
  6. this.consumer = consumer;
  7. }
  8. public final Void getRawResult() { return null; }
  9. public final void setRawResult(Void v) {}
  10. public final boolean exec() { consumer.consume(); return false; }
  11. public final void run() { consumer.consume(); }
  12. }

BufferedSubscription

  1. //基于数组的可扩展的环形缓冲区,通过CAS原子操作来实现插入和获取元素
  2. //在任何时间内最多只有一个活动的消费者任务
  3. //publisher通过锁来保证单个生产者
  4. //生成者和消费者之间的同步依赖于volatile修饰的ctl、demand、waiting变量
  5. //使用ctl管理状态
  6. //缓存区开始很小,只在需要的时候扩容
  7. //使用了Contended类避免CPU伪共享问题
  8. //当生成者和消费者以不同的速度运行时,会出现失衡,通过人为细分一些消费者方法,包括隔离所有subscriber回调
  9. @jdk.internal.vm.annotation.Contended
  10. static final class BufferedSubscription<T>
  11. implements Subscription, ForkJoinPool.ManagedBlocker {
  12. long timeout; // Long.MAX_VALUE 表示一直等待
  13. int head; // 下一个获取的位置
  14. int tail; // 下一个插入的位置
  15. final int maxCapacity; // 最大缓冲大小
  16. volatile int ctl; // 以volatile方式运行状态标志
  17. Object[] array; // 缓冲数组
  18. final Subscriber<? super T> subscriber; //消费者
  19. final BiConsumer<? super Subscriber<? super T>, ? super Throwable> onNextHandler; //用于处理异常
  20. Executor executor; // 线程池,发生错误为null
  21. Thread waiter; // 生成者线程被阻塞
  22. Throwable pendingError; // onError发生时会赋值该变量
  23. BufferedSubscription<T> next; // publisher使用
  24. BufferedSubscription<T> nextRetry; // publisher使用
  25. @jdk.internal.vm.annotation.Contended("c") // 隔离CPU缓存行
  26. volatile long demand; // 未获取的请求
  27. @jdk.internal.vm.annotation.Contended("c")
  28. volatile int waiting; // 如果生产者被阻塞,则不为零
  29. // ctl 16进制值
  30. static final int CLOSED = 0x01; // 设置了,忽略其他位
  31. static final int ACTIVE = 0x02; // 保存消费者任务一直存活
  32. static final int REQS = 0x04; // 非零请求
  33. static final int ERROR = 0x08; // 发生错误时,调用onError
  34. static final int COMPLETE = 0x10; // 当完成时,调用onComplete
  35. static final int RUN = 0x20; // 任务正在跑或刚开始跑
  36. static final int OPEN = 0x40; // 订阅后位true
  37. static final long INTERRUPTED = -1L; // 超时或者中断标志
  38. BufferedSubscription(Subscriber<? super T> subscriber,
  39. Executor executor,
  40. BiConsumer<? super Subscriber<? super T>,
  41. ? super Throwable> onNextHandler,
  42. Object[] array,
  43. int maxBufferCapacity) {
  44. this.subscriber = subscriber;
  45. this.executor = executor;
  46. this.onNextHandler = onNextHandler;
  47. this.array = array;
  48. this.maxCapacity = maxBufferCapacity;
  49. }
  50. // Wrappers for some VarHandle methods
  51. //cas更新ctl变量
  52. final boolean weakCasCtl(int cmp, int val) {
  53. return CTL.weakCompareAndSet(this, cmp, val);
  54. }
  55. //进行或计算
  56. final int getAndBitwiseOrCtl(int bits) {
  57. return (int)CTL.getAndBitwiseOr(this, bits);
  58. }
  59. //这段代码会将demand的值减去指定的k
  60. final long subtractDemand(int k) {
  61. long n = (long)(-k);
  62. //为什么还要再加n呢?
  63. return n + (long)DEMAND.getAndAdd(this, n);
  64. }
  65. //cas设置demand值
  66. final boolean casDemand(long cmp, long val) {
  67. return DEMAND.compareAndSet(this, cmp, val);
  68. }
  69. // SubmissionPublisher实用方法
  70. /**
  71. * 如果关闭了返回true (消费任务可能还在运行中).
  72. */
  73. final boolean isClosed() {
  74. return (ctl & CLOSED) != 0;
  75. }
  76. /**
  77. * 返回估计的元素数量,如果关闭了返回-1
  78. */
  79. final int estimateLag() {
  80. int c = ctl, n = tail - head;
  81. return ((c & CLOSED) != 0) ? -1 : (n < 0) ? 0 : n;
  82. }
  83. // 提交元素的方法
  84. /**
  85. * 尝试插入元素,并启动消费任务
  86. * @return 如果关闭返回-1,0表示满了
  87. */
  88. final int offer(T item, boolean unowned) {
  89. //存放元素的数组
  90. Object[] a;
  91. //cap 表示数组的容量
  92. int stat = 0, cap = ((a = array) == null) ? 0 : a.length;
  93. //i 表示要插入的索引位置;n表示已有的元素
  94. int t = tail, i = t & (cap - 1), n = t + 1 - head;
  95. if (cap > 0) {
  96. boolean added;
  97. if (n >= cap && cap < maxCapacity) // 发生扩容
  98. added = growAndOffer(item, a, t);
  99. else if (n >= cap || unowned) // 如果不是自身的线程,就说明有竞争,需要使用CAS来更新
  100. added = QA.compareAndSet(a, i, null, item);
  101. else { // 使用release 模式插入元素到数组中
  102. QA.setRelease(a, i, item);
  103. added = true;
  104. }
  105. //插入成功,tail后移一位
  106. if (added) {
  107. tail = t + 1;
  108. stat = n;
  109. }
  110. }
  111. return startOnOffer(stat); //尝试唤醒消费线程
  112. }
  113. /**
  114. * 尝试扩展缓冲区,并插入元素,成功返回true。如果内存溢出就会失败
  115. */
  116. final boolean growAndOffer(T item, Object[] a, int t) {
  117. int cap = 0, newCap = 0;
  118. Object[] newArray = null;
  119. if (a != null && (cap = a.length) > 0 && (newCap = cap << 1) > 0) { //进行两倍扩容
  120. try {
  121. newArray = new Object[newCap];
  122. } catch (OutOfMemoryError ex) {
  123. }
  124. }
  125. if (newArray == null)
  126. return false;
  127. else {
  128. //从原数组中取值,并插入新数组中
  129. int newMask = newCap - 1;
  130. newArray[t-- & newMask] = item;
  131. for (int mask = cap - 1, k = mask; k >= 0; --k) {
  132. Object x = QA.getAndSet(a, t & mask, null);
  133. if (x == null) //x为null说明已经获取
  134. break;
  135. else
  136. newArray[t-- & newMask] = x;
  137. }
  138. array = newArray;
  139. VarHandle.releaseFence(); //释放空数组
  140. return true;
  141. }
  142. }
  143. /**
  144. * 重试版本,没有扩容或者偏置
  145. */
  146. final int retryOffer(T item) {
  147. Object[] a;
  148. int stat = 0, t = tail, h = head, cap;
  149. if ((a = array) != null && (cap = a.length) > 0 &&
  150. QA.compareAndSet(a, (cap - 1) & t, null, item))
  151. //将tail后移1位
  152. stat = (tail = t + 1) - h;
  153. return startOnOffer(stat);
  154. }
  155. /**
  156. * 唤醒消费者任务
  157. * @return 如果是关闭的返回负数
  158. */
  159. final int startOnOffer(int stat) {
  160. int c; // 如果存在请求且未激活,则启动或保持活动状态
  161. if (((c = ctl) & (REQS | ACTIVE)) == REQS &&
  162. ((c = getAndBitwiseOrCtl(RUN | ACTIVE)) & (RUN | CLOSED)) == 0)
  163. //启动消费者线程
  164. tryStart();
  165. else if ((c & CLOSED) != 0)
  166. stat = -1;
  167. return stat;
  168. }
  169. /**
  170. * 启动消费的任务。 失败设置错误状态。
  171. */
  172. final void tryStart() {
  173. try {
  174. Executor e;
  175. //消费者任务
  176. ConsumerTask<T> task = new ConsumerTask<T>(this);
  177. if ((e = executor) != null) // 发生错误就跳过
  178. e.execute(task);
  179. } catch (RuntimeException | Error ex) {
  180. //设置ctl状态
  181. getAndBitwiseOrCtl(ERROR | CLOSED);
  182. throw ex;
  183. }
  184. }
  185. // 向消费者任务发信号
  186. /**
  187. * 设置给定的控制位,启动任务,如果任务没有运行或者没有关闭
  188. * @param 运行状态位
  189. */
  190. final void startOnSignal(int bits) {
  191. if ((ctl & bits) != bits &&
  192. (getAndBitwiseOrCtl(bits) & (RUN | CLOSED)) == 0)
  193. tryStart();
  194. }
  195. //订阅中
  196. final void onSubscribe() {
  197. startOnSignal(RUN | ACTIVE);
  198. }
  199. //已完成
  200. final void onComplete() {
  201. startOnSignal(RUN | ACTIVE | COMPLETE);
  202. }
  203. //发生错误
  204. final void onError(Throwable ex) {
  205. int c; Object[] a; //发生异步错误了清空缓冲区
  206. if (ex != null)
  207. pendingError = ex;
  208. if (((c = getAndBitwiseOrCtl(ERROR | RUN | ACTIVE)) & CLOSED) == 0) { //还没有关闭
  209. if ((c & RUN) == 0) //没有运行,尝试重试
  210. tryStart();
  211. else if ((a = array) != null) //清空缓冲区
  212. Arrays.fill(a, null);
  213. }
  214. }
  215. //取消
  216. public final void cancel() {
  217. onError(null);
  218. }
  219. //请求为获取的数据
  220. public final void request(long n) {
  221. if (n > 0L) {
  222. for (;;) {
  223. long p = demand, d = p + n; // saturate
  224. if (casDemand(p, d < p ? Long.MAX_VALUE : d))
  225. break;
  226. }
  227. startOnSignal(RUN | ACTIVE | REQS);
  228. }
  229. else
  230. onError(new IllegalArgumentException(
  231. "non-positive subscription request"));
  232. }
  233. // 消费者的方法
  234. /**
  235. * ConsumerTask调用,循环消费元素,或者在提交元素的时候,间接触发
  236. */
  237. final void consume() {
  238. Subscriber<? super T> s;
  239. if ((s = subscriber) != null) { // hoist checks
  240. //触发消费者,请求更多的数据
  241. subscribeOnOpen(s);
  242. long d = demand;
  243. //从数组头到尾进行循环
  244. for (int h = head, t = tail;;) {
  245. int c, taken; boolean empty;
  246. //如果发生了错误,中断消费
  247. if (((c = ctl) & ERROR) != 0) {
  248. closeOnError(s, null);
  249. break;
  250. }
  251. //一直获取元素,直到消费完或者发生错误
  252. else if ((taken = takeItems(s, d, h)) > 0) {
  253. //头指针后移
  254. head = h += taken;
  255. //修改未获取数据的局部变量demand
  256. d = subtractDemand(taken);
  257. }
  258. else if ((d = demand) == 0L && (c & REQS) != 0)
  259. weakCasCtl(c, c & ~REQS); // 已经消费完,删除ctl中的请求标志位
  260. else if (d != 0L && (c & REQS) == 0)
  261. weakCasCtl(c, c | REQS); // 有新元素需要消费,增加ctl中的请求标志位
  262. else if (t == (t = tail)) { // 稳定性检查
  263. if ((empty = (t == h)) && (c & COMPLETE) != 0) { //已经消费完了,但缓存区还没关闭
  264. closeOnComplete(s); //关闭缓存区
  265. break;
  266. }
  267. else if (empty || d == 0L) {
  268. //判断ctl运行标志是否有ACTIVE标志,有bit=ACTIVE
  269. //没有bit=RUN
  270. int bit = ((c & ACTIVE) != 0) ? ACTIVE : RUN;
  271. //删除相应的标志位,并更新ctl值,如果是RUN状态,需要退出消费任务
  272. if (weakCasCtl(c, c & ~bit) && bit == RUN)
  273. break; // 取消激活或者退出
  274. }
  275. }
  276. }
  277. }
  278. }
  279. /**
  280. * 一直消费元素直到 不可用 或者 达到边界 或者 发生错误
  281. *
  282. * @param s subscriber 消费者
  283. * @param d demand 当前需要获取的数量
  284. * @param h current head 当前的头指针位置
  285. * @return number taken 获取的数量
  286. */
  287. final int takeItems(Subscriber<? super T> s, long d, int h) {
  288. Object[] a;
  289. int k = 0, cap;
  290. if ((a = array) != null && (cap = a.length) > 0) {
  291. int m = cap - 1, b = (m >>> 3) + 1; // min(1, cap/8)
  292. int n = (d < (long)b) ? (int)d : b;
  293. for (; k < n; ++h, ++k) {
  294. //获取元素,并置为null
  295. Object x = QA.getAndSet(a, h & m, null);
  296. if (waiting != 0)
  297. //唤醒被阻塞的生成者
  298. signalWaiter();
  299. if (x == null)
  300. break;
  301. else if (!consumeNext(s, x)) //调用消费者的onNext方法,来处理元素
  302. break;
  303. }
  304. }
  305. return k;
  306. }
  307. //调用消费者的onNext方法,来处理元素
  308. final boolean consumeNext(Subscriber<? super T> s, Object x) {
  309. try {
  310. @SuppressWarnings("unchecked") T y = (T) x;
  311. if (s != null)
  312. s.onNext(y);
  313. return true;
  314. } catch (Throwable ex) {
  315. //处理异常
  316. handleOnNext(s, ex);
  317. return false;
  318. }
  319. }
  320. /**
  321. * 处理 Subscriber.onNext中的异常
  322. */
  323. final void handleOnNext(Subscriber<? super T> s, Throwable ex) {
  324. BiConsumer<? super Subscriber<? super T>, ? super Throwable> h;
  325. try {
  326. if ((h = onNextHandler) != null)
  327. //调用自定义的BiConsumer函数处理异常
  328. h.accept(s, ex);
  329. } catch (Throwable ignore) {
  330. }
  331. //关闭缓冲并调用消费者的onError方法
  332. closeOnError(s, ex);
  333. }
  334. /**
  335. * 如果是第一次执行,那么执行subscriber.onSubscribe,用于请求更多数据
  336. */
  337. final void subscribeOnOpen(Subscriber<? super T> s) {
  338. if ((ctl & OPEN) == 0 && (getAndBitwiseOrCtl(OPEN) & OPEN) == 0)
  339. consumeSubscribe(s);
  340. }
  341. //执行subscriber.onSubscribe,用于请求更多数据
  342. final void consumeSubscribe(Subscriber<? super T> s) {
  343. try {
  344. if (s != null) // ignore if disabled
  345. s.onSubscribe(this);
  346. } catch (Throwable ex) {
  347. closeOnError(s, ex);
  348. }
  349. }
  350. /**
  351. * 缓冲区还没关闭,就执行subscriber.onComplete
  352. */
  353. final void closeOnComplete(Subscriber<? super T> s) {
  354. if ((getAndBitwiseOrCtl(CLOSED) & CLOSED) == 0)
  355. consumeComplete(s);
  356. }
  357. //执行subscriber.onComplete
  358. final void consumeComplete(Subscriber<? super T> s) {
  359. try {
  360. if (s != null)
  361. s.onComplete();
  362. } catch (Throwable ignore) {
  363. }
  364. }
  365. /**
  366. * 发生错误,执行subscriber.onError,并且唤醒阻塞的生产者
  367. */
  368. final void closeOnError(Subscriber<? super T> s, Throwable ex) {
  369. if ((getAndBitwiseOrCtl(ERROR | CLOSED) & CLOSED) == 0) {
  370. if (ex == null)
  371. ex = pendingError;
  372. pendingError = null; // detach
  373. executor = null; // suppress racing start calls
  374. signalWaiter();
  375. consumeError(s, ex);
  376. }
  377. }
  378. //执行subscriber.onError
  379. final void consumeError(Subscriber<? super T> s, Throwable ex) {
  380. try {
  381. if (ex != null && s != null)
  382. s.onError(ex);
  383. } catch (Throwable ignore) {
  384. }
  385. }
  386. // 阻塞支持
  387. /**
  388. * 唤醒等待的生产者
  389. */
  390. final void signalWaiter() {
  391. Thread w;
  392. waiting = 0;
  393. if ((w = waiter) != null)
  394. LockSupport.unpark(w);
  395. }
  396. /**
  397. * 如果缓冲区关闭了,或者有可用空间,返回true
  398. */
  399. public final boolean isReleasable() {
  400. Object[] a; int cap;
  401. return ((ctl & CLOSED) != 0 ||
  402. ((a = array) != null && (cap = a.length) > 0 &&
  403. QA.getAcquire(a, (cap - 1) & tail) == null));
  404. }
  405. /**
  406. * 一直阻塞知道 timeout, closed,或者有可用空间
  407. */
  408. final void awaitSpace(long nanos) {
  409. if (!isReleasable()) {
  410. ForkJoinPool.helpAsyncBlocker(executor, this);
  411. if (!isReleasable()) {
  412. timeout = nanos;
  413. try {
  414. ForkJoinPool.managedBlock(this);
  415. } catch (InterruptedException ie) {
  416. timeout = INTERRUPTED;
  417. }
  418. if (timeout == INTERRUPTED)
  419. Thread.currentThread().interrupt();
  420. }
  421. }
  422. }
  423. /**
  424. * 给 ManagedBlocker提供的用于阻塞的方法
  425. */
  426. public final boolean block() {
  427. long nanos = timeout;
  428. boolean timed = (nanos < Long.MAX_VALUE);
  429. long deadline = timed ? System.nanoTime() + nanos : 0L;
  430. while (!isReleasable()) {
  431. if (Thread.interrupted()) {
  432. timeout = INTERRUPTED;
  433. if (timed)
  434. break;
  435. }
  436. else if (timed && (nanos = deadline - System.nanoTime()) <= 0L)
  437. break;
  438. else if (waiter == null)
  439. waiter = Thread.currentThread();
  440. else if (waiting == 0)
  441. waiting = 1;
  442. else if (timed)
  443. LockSupport.parkNanos(this, nanos);
  444. else
  445. LockSupport.park(this);
  446. }
  447. waiter = null;
  448. waiting = 0;
  449. return true;
  450. }
  451. // VarHandle mechanics 一些变量的封装对象,相当于以前调用UNSAFE的方法
  452. static final VarHandle CTL;
  453. static final VarHandle DEMAND;
  454. static final VarHandle QA;
  455. static {
  456. try {
  457. MethodHandles.Lookup l = MethodHandles.lookup();
  458. CTL = l.findVarHandle(BufferedSubscription.class, "ctl",
  459. int.class);
  460. DEMAND = l.findVarHandle(BufferedSubscription.class, "demand",
  461. long.class);
  462. QA = MethodHandles.arrayElementVarHandle(Object[].class);
  463. } catch (ReflectiveOperationException e) {
  464. throw new ExceptionInInitializerError(e);
  465. }
  466. // 减少首次加载时候的风险
  467. // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
  468. Class<?> ensureLoaded = LockSupport.class;
  469. }
  470. }

ThreadPerTaskExecutor

/**  如果ForkJoinPool.commonPool()不支持并发(公共线程池的并发级别小于1),将使用该类*/
private static final class ThreadPerTaskExecutor implements Executor {
    ThreadPerTaskExecutor() {}      // 禁止使用构造函数创建类
    public void execute(Runnable r) { new Thread(r).start(); }
}

基本方法

subscribe

//给传入的订阅者订阅,如果已经订阅,将调用订阅者的onError方法抛出IllegalStateException异常
//如果订阅成功,则会异步调用订阅者的onSubscribe方法,如果其中抛出异常,订阅将被取消
//如果SubmissionPublisher被异常关闭,那么订阅者的onError方法会被调用
//如果没有异常被关闭了,就会调用订阅者的onComplete方法
//通过调用Subscription的request方法能够接收其他更多数据
//通过调用Subscription的cancel方法取消订阅
public void subscribe(Subscriber<? super T> subscriber) {
    if (subscriber == null) throw new NullPointerException();
    // 分配初始数组
    int max = maxBufferCapacity; 
    Object[] array = new Object[max < INITIAL_CAPACITY ?
                                max : INITIAL_CAPACITY];
    BufferedSubscription<T> subscription =
        new BufferedSubscription<T>(subscriber, executor, onNextHandler,
                                    array, max);
    //同步解决了一些变量可见性问题
    synchronized (this) {
        if (!subscribed) {
            subscribed = true;
            owner = Thread.currentThread();
        }
        //循环缓冲区链表,并处理订阅
        for (BufferedSubscription<T> b = clients, pred = null;;) {
            //新的订阅者,始终会被放到链表的最后,b的变量会在循环末尾被next赋值,最后一个缓冲区的next值为null
            if (b == null) {
                Throwable ex;
                //执行消费者任务
                subscription.onSubscribe();
                if ((ex = closedException) != null)
                    //异常处理
                    subscription.onError(ex);
                else if (closed)
                    //关闭完成处理
                    subscription.onComplete();
                else if (pred == null)
                    //首次订阅
                    clients = subscription;
                else
                    //后面的订阅者缓冲区通过next连接成链表
                    pred.next = subscription;
                break;
            }
            BufferedSubscription<T> next = b.next;
            if (b.isClosed()) {   // 缓冲区关闭
                b.next = null;    // 断开该缓存区的连接
                if (pred == null)
                    clients = next;
                else
                    pred.next = next;
            }
            else if (subscriber.equals(b.subscriber)) { //重复的订阅者,抛出异常
                b.onError(new IllegalStateException("Duplicate subscribe"));
                break;
            }
            else
                pred = b;
            b = next;
        }
    }
}

submit

//将元素发布给每个订阅者,如果缓冲区已满,也会一直等待
public int submit(T item) {
    return doOffer(item, Long.MAX_VALUE, null);
}

offer

//提供了自定义BiPredicate用于判断,参数是否满足指定的要求,如果满足将有一次重试的机会
//该方法如果缓存区已满,不会一直等待
public int offer(T item,
                 BiPredicate<Subscriber<? super T>, ? super T> onDrop) {
    return doOffer(item, 0L, onDrop);
}

//跟前者比,多提供了等待超时时间,和时间单位
public int offer(T item, long timeout, TimeUnit unit,
                 BiPredicate<Subscriber<? super T>, ? super T> onDrop) {
    long nanos = unit.toNanos(timeout);
    // distinguishes from untimed (only wrt interrupt policy)
    if (nanos == Long.MAX_VALUE) --nanos;
    return doOffer(item, nanos, onDrop);
}

close

//给当前的订阅者发布onComplete信号
//并禁止后面的发布任务
//该方法无法说明所有的订阅者已经完成
public void close() {
    if (!closed) {
        BufferedSubscription<T> b;
        synchronized (this) {
            // no need to re-check closed here
            b = clients;
            clients = null;
            owner = null;
            closed = true;
        }
        //循环处理所有的缓冲区,断开连接,完成消费
        while (b != null) {
            BufferedSubscription<T> next = b.next;
            b.next = null;
            b.onComplete();
            b = next;
        }
    }
}

closeExceptionally

//给当前的订阅者发送指定的错误信号,并禁止后续发布
//该方法无法说明订阅者是否已经完成
public void closeExceptionally(Throwable error) {
    if (error == null)
        throw new NullPointerException();
    if (!closed) {
        BufferedSubscription<T> b;
        synchronized (this) {
            b = clients;
            if (!closed) {  //再次检查关闭状态,因为有可能其他线程会调用close()
                closedException = error;
                clients = null;
                owner = null;
                closed = true;
            }
        }
        while (b != null) {
            BufferedSubscription<T> next = b.next;
            b.next = null;
            b.onError(error);
            b = next;
        }
    }
}

isClosed

//是否关闭
public boolean isClosed() {
    return closed;
}

getClosedException

//获取closed异常
public Throwable getClosedException() {
    return closedException;
}

hasSubscribers

//判断是否有订阅者,只要有一个订阅者就返回true
//如果有缓冲区已经被关闭,会清理这些缓冲区
public boolean hasSubscribers() {
    boolean nonEmpty = false;
    synchronized (this) {
        for (BufferedSubscription<T> b = clients; b != null;) {
            BufferedSubscription<T> next = b.next;
            if (b.isClosed()) {
                b.next = null;
                b = clients = next;
            }
            else {
                nonEmpty = true;
                break;
            }
        }
    }
    return nonEmpty;
}

getNumberOfSubscribers

//通过缓冲区来计算还订阅的订阅者数量
public int getNumberOfSubscribers() {
    synchronized (this) {
        return cleanAndCount();
    }
}

getExecutor

//获取线程池
public Executor getExecutor() {
    return executor;
}

getMaxBufferCapacity

//获取缓冲区最大容量
public int getMaxBufferCapacity() {
    return maxBufferCapacity;
}

getSubscribers

//获取还订阅的订阅者列表,并清理缓冲区链表
public List<Subscriber<? super T>> getSubscribers() {
    ArrayList<Subscriber<? super T>> subs = new ArrayList<>();
    synchronized (this) {
        BufferedSubscription<T> pred = null, next;
        for (BufferedSubscription<T> b = clients; b != null; b = next) {
            next = b.next;
            if (b.isClosed()) {
                b.next = null;
                if (pred == null)
                    clients = next;
                else
                    pred.next = next;
            }
            else {
                subs.add(b.subscriber);
                pred = b;
            }
        }
    }
    return subs;
}

isSubscribed

//通过equals判断,指定的订阅者是否还在订阅
public boolean isSubscribed(Subscriber<? super T> subscriber) {
    if (subscriber == null) throw new NullPointerException();
    if (!closed) {
        synchronized (this) {
            BufferedSubscription<T> pred = null, next;
            for (BufferedSubscription<T> b = clients; b != null; b = next) {
                next = b.next;
                if (b.isClosed()) {
                    b.next = null;
                    if (pred == null)
                        clients = next;
                    else
                        pred.next = next;
                }
                else if (subscriber.equals(b.subscriber))
                    return true;
                else
                    pred = b;
            }
        }
    }
    return false;
}

estimateMinimumDemand

//返回所有的订阅者中,还没有消费的最少元素数量
public long estimateMinimumDemand() {
    long min = Long.MAX_VALUE;
    boolean nonEmpty = false;
    synchronized (this) {
        BufferedSubscription<T> pred = null, next;
        for (BufferedSubscription<T> b = clients; b != null; b = next) {
            int n; long d;
            next = b.next;
            if ((n = b.estimateLag()) < 0) {
                b.next = null;
                if (pred == null)
                    clients = next;
                else
                    pred.next = next;
            }
            else {
                if ((d = b.demand - n) < min)
                    min = d;
                nonEmpty = true;
                pred = b;
            }
        }
    }
    return nonEmpty ? min : 0;
}

estimateMaximumLag

//返回所有的订阅者中,还没有消费的最多元素数量
public int estimateMaximumLag() {
    int max = 0;
    synchronized (this) {
        BufferedSubscription<T> pred = null, next;
        for (BufferedSubscription<T> b = clients; b != null; b = next) {
            int n;
            next = b.next;
            if ((n = b.estimateLag()) < 0) {
                b.next = null;
                if (pred == null)
                    clients = next;
                else
                    pred.next = next;
            }
            else {
                if (n > max)
                    max = n;
                pred = b;
            }
        }
    }
    return max;
}

consume

//公开的消费方法
public CompletableFuture<Void> consume(Consumer<? super T> consumer) {
    if (consumer == null)
        throw new NullPointerException();
    CompletableFuture<Void> status = new CompletableFuture<>();
    subscribe(new ConsumerSubscriber<T>(status, consumer));
    return status;
}

roundCapacity

//计算最大容量的算法
static final int roundCapacity(int cap) {
    int n = cap - 1;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    return (n <= 0) ? 1 : // at least 1
        (n >= BUFFER_CAPACITY_LIMIT) ? BUFFER_CAPACITY_LIMIT : n + 1;
}

doOffer

//submit 和offer的公共实现
//submit方法nanos == Long.MAX_VALUE
private int doOffer(T item, long nanos,
                    BiPredicate<Subscriber<? super T>, ? super T> onDrop) {
    if (item == null) throw new NullPointerException();
    int lag = 0;
    boolean complete, unowned;
    synchronized (this) {
        Thread t = Thread.currentThread(), o;
        BufferedSubscription<T> b = clients;
        if ((unowned = ((o = owner) != t)) && o != null)
            owner = null;                     // disable bias
        if (b == null)
            complete = closed;
        else {
            complete = false;
            boolean cleanMe = false;
            BufferedSubscription<T> retries = null, rtail = null, next;
            do {
                next = b.next;
                int stat = b.offer(item, unowned);
                if (stat == 0) {              // 缓冲区已满,加入重试列表
                    b.nextRetry = null;       // 先重置原来的nextRetry变量
                    if (rtail == null)
                        retries = b;
                    else
                        rtail.nextRetry = b;
                    rtail = b;
                }
                else if (stat < 0)            // 缓存区已经关闭
                    cleanMe = true;           // 标记清理,将在后面清理
                else if (stat > lag)
                    lag = stat;
            } while ((b = next) != null);  //循环处理,直到处理完成

            if (retries != null || cleanMe)  //重试列表不为空,或者清理标志为true
                //重试发布
                lag = retryOffer(item, nanos, onDrop, retries, lag, cleanMe);
        }
    }
    //已经关闭抛出异常Closed
    if (complete)
        throw new IllegalStateException("Closed");
    else
        return lag;
}

retryOffer

//重试发布元素
private int retryOffer(T item, long nanos,
                       BiPredicate<Subscriber<? super T>, ? super T> onDrop,
                       BufferedSubscription<T> retries, int lag,
                       boolean cleanMe) {
    for (BufferedSubscription<T> r = retries; r != null;) {
        BufferedSubscription<T> nextRetry = r.nextRetry;
        //将缓冲区存入临时变量后,及时断开连接
        r.nextRetry = null;
        if (nanos > 0L)
            //阻塞等待
            r.awaitSpace(nanos);
        //重试发布
        int stat = r.retryOffer(item);
        //如果还是发布失败,但自定义了BiPredicate函数,会根据自定义规则进行判断,为true会再重试一次
        if (stat == 0 && onDrop != null && onDrop.test(r.subscriber, item))
            stat = r.retryOffer(item);
        if (stat == 0) //缓冲区满了
            lag = (lag >= 0) ? -1 : lag - 1;   //这里有点奇怪?
        else if (stat < 0)  //关闭了,标志为清理
            cleanMe = true;
        else if (lag >= 0 && stat > lag)
            lag = stat;
        r = nextRetry;
    }
    if (cleanMe)
        cleanAndCount();
    return lag;
}

cleanAndCount

//清理缓存区链表并计算还在订阅的订阅者数量
private int cleanAndCount() {
    int count = 0;
    BufferedSubscription<T> pred = null, next;
    for (BufferedSubscription<T> b = clients; b != null; b = next) {
        next = b.next;
        if (b.isClosed()) {
            b.next = null;
            if (pred == null)
                clients = next;
            else
                pred.next = next;
        }
        else {
            pred = b;
            ++count;
        }
    }
    return count;
}

瓦雀