1 /* 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 * 4 * This code is free software; you can redistribute it and/or modify it 5 * under the terms of the GNU General Public License version 2 only, as 6 * published by the Free Software Foundation. Oracle designates this 7 * particular file as subject to the "Classpath" exception as provided 8 * by Oracle in the LICENSE file that accompanied this code. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 */ 24 25 /* 26 * This file is available under and governed by the GNU General Public 27 * License version 2 only, as published by the Free Software Foundation. 28 * However, the following notice accompanied the original version of this 29 * file: 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/publicdomain/zero/1.0/ 34 */ 35 36 package java.util.concurrent; 37 38 import java.lang.invoke.MethodHandles; 39 import java.lang.invoke.VarHandle; 40 import java.util.ArrayList; 41 import java.util.Arrays; 42 import java.util.List; 43 import java.util.concurrent.locks.LockSupport; 44 import java.util.function.BiConsumer; 45 import java.util.function.BiPredicate; 46 import java.util.function.Consumer; 47 import static java.util.concurrent.Flow.Publisher; 48 import static java.util.concurrent.Flow.Subscriber; 49 import static java.util.concurrent.Flow.Subscription; 50 51 /** 52 * A {@link Flow.Publisher} that asynchronously issues submitted 53 * (non-null) items to current subscribers until it is closed. Each 54 * current subscriber receives newly submitted items in the same order 55 * unless drops or exceptions are encountered. Using a 56 * SubmissionPublisher allows item generators to act as compliant <a 57 * href="http://www.reactive-streams.org/"> reactive-streams</a> 58 * Publishers relying on drop handling and/or blocking for flow 59 * control. 60 * 61 * <p>A SubmissionPublisher uses the {@link Executor} supplied in its 62 * constructor for delivery to subscribers. The best choice of 63 * Executor depends on expected usage. If the generator(s) of 64 * submitted items run in separate threads, and the number of 65 * subscribers can be estimated, consider using a {@link 66 * Executors#newFixedThreadPool}. Otherwise consider using the 67 * default, normally the {@link ForkJoinPool#commonPool}. 68 * 69 * <p>Buffering allows producers and consumers to transiently operate 70 * at different rates. Each subscriber uses an independent buffer. 71 * Buffers are created upon first use and expanded as needed up to the 72 * given maximum. (The enforced capacity may be rounded up to the 73 * nearest power of two and/or bounded by the largest value supported 74 * by this implementation.) Invocations of {@link 75 * Flow.Subscription#request(long) request} do not directly result in 76 * buffer expansion, but risk saturation if unfilled requests exceed 77 * the maximum capacity. The default value of {@link 78 * Flow#defaultBufferSize()} may provide a useful starting point for 79 * choosing a capacity based on expected rates, resources, and usages. 80 * 81 * <p>A single SubmissionPublisher may be shared among multiple 82 * sources. Actions in a source thread prior to publishing an item or 83 * issuing a signal <a href="package-summary.html#MemoryVisibility"> 84 * <i>happen-before</i></a> actions subsequent to the corresponding 85 * access by each subscriber. But reported estimates of lag and demand 86 * are designed for use in monitoring, not for synchronization 87 * control, and may reflect stale or inaccurate views of progress. 88 * 89 * <p>Publication methods support different policies about what to do 90 * when buffers are saturated. Method {@link #submit(Object) submit} 91 * blocks until resources are available. This is simplest, but least 92 * responsive. The {@code offer} methods may drop items (either 93 * immediately or with bounded timeout), but provide an opportunity to 94 * interpose a handler and then retry. 95 * 96 * <p>If any Subscriber method throws an exception, its subscription 97 * is cancelled. If a handler is supplied as a constructor argument, 98 * it is invoked before cancellation upon an exception in method 99 * {@link Flow.Subscriber#onNext onNext}, but exceptions in methods 100 * {@link Flow.Subscriber#onSubscribe onSubscribe}, 101 * {@link Flow.Subscriber#onError(Throwable) onError} and 102 * {@link Flow.Subscriber#onComplete() onComplete} are not recorded or 103 * handled before cancellation. If the supplied Executor throws 104 * {@link RejectedExecutionException} (or any other RuntimeException 105 * or Error) when attempting to execute a task, or a drop handler 106 * throws an exception when processing a dropped item, then the 107 * exception is rethrown. In these cases, not all subscribers will 108 * have been issued the published item. It is usually good practice to 109 * {@link #closeExceptionally closeExceptionally} in these cases. 110 * 111 * <p>Method {@link #consume(Consumer)} simplifies support for a 112 * common case in which the only action of a subscriber is to request 113 * and process all items using a supplied function. 114 * 115 * <p>This class may also serve as a convenient base for subclasses 116 * that generate items, and use the methods in this class to publish 117 * them. For example here is a class that periodically publishes the 118 * items generated from a supplier. (In practice you might add methods 119 * to independently start and stop generation, to share Executors 120 * among publishers, and so on, or use a SubmissionPublisher as a 121 * component rather than a superclass.) 122 * 123 * <pre> {@code 124 * class PeriodicPublisher<T> extends SubmissionPublisher<T> { 125 * final ScheduledFuture<?> periodicTask; 126 * final ScheduledExecutorService scheduler; 127 * PeriodicPublisher(Executor executor, int maxBufferCapacity, 128 * Supplier<? extends T> supplier, 129 * long period, TimeUnit unit) { 130 * super(executor, maxBufferCapacity); 131 * scheduler = new ScheduledThreadPoolExecutor(1); 132 * periodicTask = scheduler.scheduleAtFixedRate( 133 * () -> submit(supplier.get()), 0, period, unit); 134 * } 135 * public void close() { 136 * periodicTask.cancel(false); 137 * scheduler.shutdown(); 138 * super.close(); 139 * } 140 * }}</pre> 141 * 142 * <p>Here is an example of a {@link Flow.Processor} implementation. 143 * It uses single-step requests to its publisher for simplicity of 144 * illustration. A more adaptive version could monitor flow using the 145 * lag estimate returned from {@code submit}, along with other utility 146 * methods. 147 * 148 * <pre> {@code 149 * class TransformProcessor<S,T> extends SubmissionPublisher<T> 150 * implements Flow.Processor<S,T> { 151 * final Function<? super S, ? extends T> function; 152 * Flow.Subscription subscription; 153 * TransformProcessor(Executor executor, int maxBufferCapacity, 154 * Function<? super S, ? extends T> function) { 155 * super(executor, maxBufferCapacity); 156 * this.function = function; 157 * } 158 * public void onSubscribe(Flow.Subscription subscription) { 159 * (this.subscription = subscription).request(1); 160 * } 161 * public void onNext(S item) { 162 * subscription.request(1); 163 * submit(function.apply(item)); 164 * } 165 * public void onError(Throwable ex) { closeExceptionally(ex); } 166 * public void onComplete() { close(); } 167 * }}</pre> 168 * 169 * @param <T> the published item type 170 * @author Doug Lea 171 * @since 9 172 */ 173 public class SubmissionPublisher<T> implements Publisher<T>, 174 AutoCloseable { 175 /* 176 * Most mechanics are handled by BufferedSubscription. This class 177 * mainly tracks subscribers and ensures sequentiality, by using 178 * built-in synchronization locks across public methods. Using 179 * built-in locks works well in the most typical case in which 180 * only one thread submits items. We extend this idea in 181 * submission methods by detecting single-ownership to reduce 182 * producer-consumer synchronization strength. 183 */ 184 185 /** The largest possible power of two array size. */ 186 static final int BUFFER_CAPACITY_LIMIT = 1 << 30; 187 188 /** 189 * Initial buffer capacity used when maxBufferCapacity is 190 * greater. Must be a power of two. 191 */ 192 static final int INITIAL_CAPACITY = 32; 193 194 /** Round capacity to power of 2, at most limit. */ 195 static final int roundCapacity(int cap) { 196 int n = cap - 1; 197 n |= n >>> 1; 198 n |= n >>> 2; 199 n |= n >>> 4; 200 n |= n >>> 8; 201 n |= n >>> 16; 202 return (n <= 0) ? 1 : // at least 1 203 (n >= BUFFER_CAPACITY_LIMIT) ? BUFFER_CAPACITY_LIMIT : n + 1; 204 } 205 206 // default Executor setup; nearly the same as CompletableFuture 207 208 /** 209 * Default executor -- ForkJoinPool.commonPool() unless it cannot 210 * support parallelism. 211 */ 212 private static final Executor ASYNC_POOL = 213 (ForkJoinPool.getCommonPoolParallelism() > 1) ? 214 ForkJoinPool.commonPool() : new ThreadPerTaskExecutor(); 215 216 /** Fallback if ForkJoinPool.commonPool() cannot support parallelism */ 217 private static final class ThreadPerTaskExecutor implements Executor { 218 ThreadPerTaskExecutor() {} // prevent access constructor creation 219 public void execute(Runnable r) { new Thread(r).start(); } 220 } 221 222 /** 223 * Clients (BufferedSubscriptions) are maintained in a linked list 224 * (via their "next" fields). This works well for publish loops. 225 * It requires O(n) traversal to check for duplicate subscribers, 226 * but we expect that subscribing is much less common than 227 * publishing. Unsubscribing occurs only during traversal loops, 228 * when BufferedSubscription methods return negative values 229 * signifying that they have been closed. To reduce 230 * head-of-line blocking, submit and offer methods first call 231 * BufferedSubscription.offer on each subscriber, and place 232 * saturated ones in retries list (using nextRetry field), and 233 * retry, possibly blocking or dropping. 234 */ 235 BufferedSubscription<T> clients; 236 237 /** Run status, updated only within locks */ 238 volatile boolean closed; 239 /** Set true on first call to subscribe, to initialize possible owner */ 240 boolean subscribed; 241 /** The first caller thread to subscribe, or null if thread ever changed */ 242 Thread owner; 243 /** If non-null, the exception in closeExceptionally */ 244 volatile Throwable closedException; 245 246 // Parameters for constructing BufferedSubscriptions 247 final Executor executor; 248 final BiConsumer<? super Subscriber<? super T>, ? super Throwable> onNextHandler; 249 final int maxBufferCapacity; 250 251 /** 252 * Creates a new SubmissionPublisher using the given Executor for 253 * async delivery to subscribers, with the given maximum buffer size 254 * for each subscriber, and, if non-null, the given handler invoked 255 * when any Subscriber throws an exception in method {@link 256 * Flow.Subscriber#onNext(Object) onNext}. 257 * 258 * @param executor the executor to use for async delivery, 259 * supporting creation of at least one independent thread 260 * @param maxBufferCapacity the maximum capacity for each 261 * subscriber's buffer (the enforced capacity may be rounded up to 262 * the nearest power of two and/or bounded by the largest value 263 * supported by this implementation; method {@link #getMaxBufferCapacity} 264 * returns the actual value) 265 * @param handler if non-null, procedure to invoke upon exception 266 * thrown in method {@code onNext} 267 * @throws NullPointerException if executor is null 268 * @throws IllegalArgumentException if maxBufferCapacity not 269 * positive 270 */ 271 public SubmissionPublisher(Executor executor, int maxBufferCapacity, 272 BiConsumer<? super Subscriber<? super T>, ? super Throwable> handler) { 273 if (executor == null) 274 throw new NullPointerException(); 275 if (maxBufferCapacity <= 0) 276 throw new IllegalArgumentException("capacity must be positive"); 277 this.executor = executor; 278 this.onNextHandler = handler; 279 this.maxBufferCapacity = roundCapacity(maxBufferCapacity); 280 } 281 282 /** 283 * Creates a new SubmissionPublisher using the given Executor for 284 * async delivery to subscribers, with the given maximum buffer size 285 * for each subscriber, and no handler for Subscriber exceptions in 286 * method {@link Flow.Subscriber#onNext(Object) onNext}. 287 * 288 * @param executor the executor to use for async delivery, 289 * supporting creation of at least one independent thread 290 * @param maxBufferCapacity the maximum capacity for each 291 * subscriber's buffer (the enforced capacity may be rounded up to 292 * the nearest power of two and/or bounded by the largest value 293 * supported by this implementation; method {@link #getMaxBufferCapacity} 294 * returns the actual value) 295 * @throws NullPointerException if executor is null 296 * @throws IllegalArgumentException if maxBufferCapacity not 297 * positive 298 */ 299 public SubmissionPublisher(Executor executor, int maxBufferCapacity) { 300 this(executor, maxBufferCapacity, null); 301 } 302 303 /** 304 * Creates a new SubmissionPublisher using the {@link 305 * ForkJoinPool#commonPool()} for async delivery to subscribers 306 * (unless it does not support a parallelism level of at least two, 307 * in which case, a new Thread is created to run each task), with 308 * maximum buffer capacity of {@link Flow#defaultBufferSize}, and no 309 * handler for Subscriber exceptions in method {@link 310 * Flow.Subscriber#onNext(Object) onNext}. 311 */ 312 public SubmissionPublisher() { 313 this(ASYNC_POOL, Flow.defaultBufferSize(), null); 314 } 315 316 /** 317 * Adds the given Subscriber unless already subscribed. If already 318 * subscribed, the Subscriber's {@link 319 * Flow.Subscriber#onError(Throwable) onError} method is invoked on 320 * the existing subscription with an {@link IllegalStateException}. 321 * Otherwise, upon success, the Subscriber's {@link 322 * Flow.Subscriber#onSubscribe onSubscribe} method is invoked 323 * asynchronously with a new {@link Flow.Subscription}. If {@link 324 * Flow.Subscriber#onSubscribe onSubscribe} throws an exception, the 325 * subscription is cancelled. Otherwise, if this SubmissionPublisher 326 * was closed exceptionally, then the subscriber's {@link 327 * Flow.Subscriber#onError onError} method is invoked with the 328 * corresponding exception, or if closed without exception, the 329 * subscriber's {@link Flow.Subscriber#onComplete() onComplete} 330 * method is invoked. Subscribers may enable receiving items by 331 * invoking the {@link Flow.Subscription#request(long) request} 332 * method of the new Subscription, and may unsubscribe by invoking 333 * its {@link Flow.Subscription#cancel() cancel} method. 334 * 335 * @param subscriber the subscriber 336 * @throws NullPointerException if subscriber is null 337 */ 338 public void subscribe(Subscriber<? super T> subscriber) { 339 if (subscriber == null) throw new NullPointerException(); 340 int max = maxBufferCapacity; // allocate initial array 341 Object[] array = new Object[max < INITIAL_CAPACITY ? 342 max : INITIAL_CAPACITY]; 343 BufferedSubscription<T> subscription = 344 new BufferedSubscription<T>(subscriber, executor, onNextHandler, 345 array, max); 346 synchronized (this) { 347 if (!subscribed) { 348 subscribed = true; 349 owner = Thread.currentThread(); 350 } 351 for (BufferedSubscription<T> b = clients, pred = null;;) { 352 if (b == null) { 353 Throwable ex; 354 subscription.onSubscribe(); 355 if ((ex = closedException) != null) 356 subscription.onError(ex); 357 else if (closed) 358 subscription.onComplete(); 359 else if (pred == null) 360 clients = subscription; 361 else 362 pred.next = subscription; 363 break; 364 } 365 BufferedSubscription<T> next = b.next; 366 if (b.isClosed()) { // remove 367 b.next = null; // detach 368 if (pred == null) 369 clients = next; 370 else 371 pred.next = next; 372 } 373 else if (subscriber.equals(b.subscriber)) { 374 b.onError(new IllegalStateException("Duplicate subscribe")); 375 break; 376 } 377 else 378 pred = b; 379 b = next; 380 } 381 } 382 } 383 384 /** 385 * Common implementation for all three forms of submit and offer. 386 * Acts as submit if nanos == Long.MAX_VALUE, else offer. 387 */ 388 private int doOffer(T item, long nanos, 389 BiPredicate<Subscriber<? super T>, ? super T> onDrop) { 390 if (item == null) throw new NullPointerException(); 391 int lag = 0; 392 boolean complete, unowned; 393 synchronized (this) { 394 Thread t = Thread.currentThread(), o; 395 BufferedSubscription<T> b = clients; 396 if ((unowned = ((o = owner) != t)) && o != null) 397 owner = null; // disable bias 398 if (b == null) 399 complete = closed; 400 else { 401 complete = false; 402 boolean cleanMe = false; 403 BufferedSubscription<T> retries = null, rtail = null, next; 404 do { 405 next = b.next; 406 int stat = b.offer(item, unowned); 407 if (stat == 0) { // saturated; add to retry list 408 b.nextRetry = null; // avoid garbage on exceptions 409 if (rtail == null) 410 retries = b; 411 else 412 rtail.nextRetry = b; 413 rtail = b; 414 } 415 else if (stat < 0) // closed 416 cleanMe = true; // remove later 417 else if (stat > lag) 418 lag = stat; 419 } while ((b = next) != null); 420 421 if (retries != null || cleanMe) 422 lag = retryOffer(item, nanos, onDrop, retries, lag, cleanMe); 423 } 424 } 425 if (complete) 426 throw new IllegalStateException("Closed"); 427 else 428 return lag; 429 } 430 431 /** 432 * Helps, (timed) waits for, and/or drops buffers on list; returns 433 * lag or negative drops (for use in offer). 434 */ 435 private int retryOffer(T item, long nanos, 436 BiPredicate<Subscriber<? super T>, ? super T> onDrop, 437 BufferedSubscription<T> retries, int lag, 438 boolean cleanMe) { 439 for (BufferedSubscription<T> r = retries; r != null;) { 440 BufferedSubscription<T> nextRetry = r.nextRetry; 441 r.nextRetry = null; 442 if (nanos > 0L) 443 r.awaitSpace(nanos); 444 int stat = r.retryOffer(item); 445 if (stat == 0 && onDrop != null && onDrop.test(r.subscriber, item)) 446 stat = r.retryOffer(item); 447 if (stat == 0) 448 lag = (lag >= 0) ? -1 : lag - 1; 449 else if (stat < 0) 450 cleanMe = true; 451 else if (lag >= 0 && stat > lag) 452 lag = stat; 453 r = nextRetry; 454 } 455 if (cleanMe) 456 cleanAndCount(); 457 return lag; 458 } 459 460 /** 461 * Returns current list count after removing closed subscribers. 462 * Call only while holding lock. Used mainly by retryOffer for 463 * cleanup. 464 */ 465 private int cleanAndCount() { 466 int count = 0; 467 BufferedSubscription<T> pred = null, next; 468 for (BufferedSubscription<T> b = clients; b != null; b = next) { 469 next = b.next; 470 if (b.isClosed()) { 471 b.next = null; 472 if (pred == null) 473 clients = next; 474 else 475 pred.next = next; 476 } 477 else { 478 pred = b; 479 ++count; 480 } 481 } 482 return count; 483 } 484 485 /** 486 * Publishes the given item to each current subscriber by 487 * asynchronously invoking its {@link Flow.Subscriber#onNext(Object) 488 * onNext} method, blocking uninterruptibly while resources for any 489 * subscriber are unavailable. This method returns an estimate of 490 * the maximum lag (number of items submitted but not yet consumed) 491 * among all current subscribers. This value is at least one 492 * (accounting for this submitted item) if there are any 493 * subscribers, else zero. 494 * 495 * <p>If the Executor for this publisher throws a 496 * RejectedExecutionException (or any other RuntimeException or 497 * Error) when attempting to asynchronously notify subscribers, 498 * then this exception is rethrown, in which case not all 499 * subscribers will have been issued this item. 500 * 501 * @param item the (non-null) item to publish 502 * @return the estimated maximum lag among subscribers 503 * @throws IllegalStateException if closed 504 * @throws NullPointerException if item is null 505 * @throws RejectedExecutionException if thrown by Executor 506 */ 507 public int submit(T item) { 508 return doOffer(item, Long.MAX_VALUE, null); 509 } 510 511 /** 512 * Publishes the given item, if possible, to each current subscriber 513 * by asynchronously invoking its {@link 514 * Flow.Subscriber#onNext(Object) onNext} method. The item may be 515 * dropped by one or more subscribers if resource limits are 516 * exceeded, in which case the given handler (if non-null) is 517 * invoked, and if it returns true, retried once. Other calls to 518 * methods in this class by other threads are blocked while the 519 * handler is invoked. Unless recovery is assured, options are 520 * usually limited to logging the error and/or issuing an {@link 521 * Flow.Subscriber#onError(Throwable) onError} signal to the 522 * subscriber. 523 * 524 * <p>This method returns a status indicator: If negative, it 525 * represents the (negative) number of drops (failed attempts to 526 * issue the item to a subscriber). Otherwise it is an estimate of 527 * the maximum lag (number of items submitted but not yet 528 * consumed) among all current subscribers. This value is at least 529 * one (accounting for this submitted item) if there are any 530 * subscribers, else zero. 531 * 532 * <p>If the Executor for this publisher throws a 533 * RejectedExecutionException (or any other RuntimeException or 534 * Error) when attempting to asynchronously notify subscribers, or 535 * the drop handler throws an exception when processing a dropped 536 * item, then this exception is rethrown. 537 * 538 * @param item the (non-null) item to publish 539 * @param onDrop if non-null, the handler invoked upon a drop to a 540 * subscriber, with arguments of the subscriber and item; if it 541 * returns true, an offer is re-attempted (once) 542 * @return if negative, the (negative) number of drops; otherwise 543 * an estimate of maximum lag 544 * @throws IllegalStateException if closed 545 * @throws NullPointerException if item is null 546 * @throws RejectedExecutionException if thrown by Executor 547 */ 548 public int offer(T item, 549 BiPredicate<Subscriber<? super T>, ? super T> onDrop) { 550 return doOffer(item, 0L, onDrop); 551 } 552 553 /** 554 * Publishes the given item, if possible, to each current subscriber 555 * by asynchronously invoking its {@link 556 * Flow.Subscriber#onNext(Object) onNext} method, blocking while 557 * resources for any subscription are unavailable, up to the 558 * specified timeout or until the caller thread is interrupted, at 559 * which point the given handler (if non-null) is invoked, and if it 560 * returns true, retried once. (The drop handler may distinguish 561 * timeouts from interrupts by checking whether the current thread 562 * is interrupted.) Other calls to methods in this class by other 563 * threads are blocked while the handler is invoked. Unless 564 * recovery is assured, options are usually limited to logging the 565 * error and/or issuing an {@link Flow.Subscriber#onError(Throwable) 566 * onError} signal to the subscriber. 567 * 568 * <p>This method returns a status indicator: If negative, it 569 * represents the (negative) number of drops (failed attempts to 570 * issue the item to a subscriber). Otherwise it is an estimate of 571 * the maximum lag (number of items submitted but not yet 572 * consumed) among all current subscribers. This value is at least 573 * one (accounting for this submitted item) if there are any 574 * subscribers, else zero. 575 * 576 * <p>If the Executor for this publisher throws a 577 * RejectedExecutionException (or any other RuntimeException or 578 * Error) when attempting to asynchronously notify subscribers, or 579 * the drop handler throws an exception when processing a dropped 580 * item, then this exception is rethrown. 581 * 582 * @param item the (non-null) item to publish 583 * @param timeout how long to wait for resources for any subscriber 584 * before giving up, in units of {@code unit} 585 * @param unit a {@code TimeUnit} determining how to interpret the 586 * {@code timeout} parameter 587 * @param onDrop if non-null, the handler invoked upon a drop to a 588 * subscriber, with arguments of the subscriber and item; if it 589 * returns true, an offer is re-attempted (once) 590 * @return if negative, the (negative) number of drops; otherwise 591 * an estimate of maximum lag 592 * @throws IllegalStateException if closed 593 * @throws NullPointerException if item is null 594 * @throws RejectedExecutionException if thrown by Executor 595 */ 596 public int offer(T item, long timeout, TimeUnit unit, 597 BiPredicate<Subscriber<? super T>, ? super T> onDrop) { 598 long nanos = unit.toNanos(timeout); 599 // distinguishes from untimed (only wrt interrupt policy) 600 if (nanos == Long.MAX_VALUE) --nanos; 601 return doOffer(item, nanos, onDrop); 602 } 603 604 /** 605 * Unless already closed, issues {@link 606 * Flow.Subscriber#onComplete() onComplete} signals to current 607 * subscribers, and disallows subsequent attempts to publish. 608 * Upon return, this method does <em>NOT</em> guarantee that all 609 * subscribers have yet completed. 610 */ 611 public void close() { 612 if (!closed) { 613 BufferedSubscription<T> b; 614 synchronized (this) { 615 // no need to re-check closed here 616 b = clients; 617 clients = null; 618 owner = null; 619 closed = true; 620 } 621 while (b != null) { 622 BufferedSubscription<T> next = b.next; 623 b.next = null; 624 b.onComplete(); 625 b = next; 626 } 627 } 628 } 629 630 /** 631 * Unless already closed, issues {@link 632 * Flow.Subscriber#onError(Throwable) onError} signals to current 633 * subscribers with the given error, and disallows subsequent 634 * attempts to publish. Future subscribers also receive the given 635 * error. Upon return, this method does <em>NOT</em> guarantee 636 * that all subscribers have yet completed. 637 * 638 * @param error the {@code onError} argument sent to subscribers 639 * @throws NullPointerException if error is null 640 */ 641 public void closeExceptionally(Throwable error) { 642 if (error == null) 643 throw new NullPointerException(); 644 if (!closed) { 645 BufferedSubscription<T> b; 646 synchronized (this) { 647 b = clients; 648 if (!closed) { // don't clobber racing close 649 closedException = error; 650 clients = null; 651 owner = null; 652 closed = true; 653 } 654 } 655 while (b != null) { 656 BufferedSubscription<T> next = b.next; 657 b.next = null; 658 b.onError(error); 659 b = next; 660 } 661 } 662 } 663 664 /** 665 * Returns true if this publisher is not accepting submissions. 666 * 667 * @return true if closed 668 */ 669 public boolean isClosed() { 670 return closed; 671 } 672 673 /** 674 * Returns the exception associated with {@link 675 * #closeExceptionally(Throwable) closeExceptionally}, or null if 676 * not closed or if closed normally. 677 * 678 * @return the exception, or null if none 679 */ 680 public Throwable getClosedException() { 681 return closedException; 682 } 683 684 /** 685 * Returns true if this publisher has any subscribers. 686 * 687 * @return true if this publisher has any subscribers 688 */ 689 public boolean hasSubscribers() { 690 boolean nonEmpty = false; 691 synchronized (this) { 692 for (BufferedSubscription<T> b = clients; b != null;) { 693 BufferedSubscription<T> next = b.next; 694 if (b.isClosed()) { 695 b.next = null; 696 b = clients = next; 697 } 698 else { 699 nonEmpty = true; 700 break; 701 } 702 } 703 } 704 return nonEmpty; 705 } 706 707 /** 708 * Returns the number of current subscribers. 709 * 710 * @return the number of current subscribers 711 */ 712 public int getNumberOfSubscribers() { 713 synchronized (this) { 714 return cleanAndCount(); 715 } 716 } 717 718 /** 719 * Returns the Executor used for asynchronous delivery. 720 * 721 * @return the Executor used for asynchronous delivery 722 */ 723 public Executor getExecutor() { 724 return executor; 725 } 726 727 /** 728 * Returns the maximum per-subscriber buffer capacity. 729 * 730 * @return the maximum per-subscriber buffer capacity 731 */ 732 public int getMaxBufferCapacity() { 733 return maxBufferCapacity; 734 } 735 736 /** 737 * Returns a list of current subscribers for monitoring and 738 * tracking purposes, not for invoking {@link Flow.Subscriber} 739 * methods on the subscribers. 740 * 741 * @return list of current subscribers 742 */ 743 public List<Subscriber<? super T>> getSubscribers() { 744 ArrayList<Subscriber<? super T>> subs = new ArrayList<>(); 745 synchronized (this) { 746 BufferedSubscription<T> pred = null, next; 747 for (BufferedSubscription<T> b = clients; b != null; b = next) { 748 next = b.next; 749 if (b.isClosed()) { 750 b.next = null; 751 if (pred == null) 752 clients = next; 753 else 754 pred.next = next; 755 } 756 else 757 subs.add(b.subscriber); 758 } 759 } 760 return subs; 761 } 762 763 /** 764 * Returns true if the given Subscriber is currently subscribed. 765 * 766 * @param subscriber the subscriber 767 * @return true if currently subscribed 768 * @throws NullPointerException if subscriber is null 769 */ 770 public boolean isSubscribed(Subscriber<? super T> subscriber) { 771 if (subscriber == null) throw new NullPointerException(); 772 if (!closed) { 773 synchronized (this) { 774 BufferedSubscription<T> pred = null, next; 775 for (BufferedSubscription<T> b = clients; b != null; b = next) { 776 next = b.next; 777 if (b.isClosed()) { 778 b.next = null; 779 if (pred == null) 780 clients = next; 781 else 782 pred.next = next; 783 } 784 else if (subscriber.equals(b.subscriber)) 785 return true; 786 else 787 pred = b; 788 } 789 } 790 } 791 return false; 792 } 793 794 /** 795 * Returns an estimate of the minimum number of items requested 796 * (via {@link Flow.Subscription#request(long) request}) but not 797 * yet produced, among all current subscribers. 798 * 799 * @return the estimate, or zero if no subscribers 800 */ 801 public long estimateMinimumDemand() { 802 long min = Long.MAX_VALUE; 803 boolean nonEmpty = false; 804 synchronized (this) { 805 BufferedSubscription<T> pred = null, next; 806 for (BufferedSubscription<T> b = clients; b != null; b = next) { 807 int n; long d; 808 next = b.next; 809 if ((n = b.estimateLag()) < 0) { 810 b.next = null; 811 if (pred == null) 812 clients = next; 813 else 814 pred.next = next; 815 } 816 else { 817 if ((d = b.demand - n) < min) 818 min = d; 819 nonEmpty = true; 820 pred = b; 821 } 822 } 823 } 824 return nonEmpty ? min : 0; 825 } 826 827 /** 828 * Returns an estimate of the maximum number of items produced but 829 * not yet consumed among all current subscribers. 830 * 831 * @return the estimate 832 */ 833 public int estimateMaximumLag() { 834 int max = 0; 835 synchronized (this) { 836 BufferedSubscription<T> pred = null, next; 837 for (BufferedSubscription<T> b = clients; b != null; b = next) { 838 int n; 839 next = b.next; 840 if ((n = b.estimateLag()) < 0) { 841 b.next = null; 842 if (pred == null) 843 clients = next; 844 else 845 pred.next = next; 846 } 847 else { 848 if (n > max) 849 max = n; 850 pred = b; 851 } 852 } 853 } 854 return max; 855 } 856 857 /** 858 * Processes all published items using the given Consumer function. 859 * Returns a CompletableFuture that is completed normally when this 860 * publisher signals {@link Flow.Subscriber#onComplete() 861 * onComplete}, or completed exceptionally upon any error, or an 862 * exception is thrown by the Consumer, or the returned 863 * CompletableFuture is cancelled, in which case no further items 864 * are processed. 865 * 866 * @param consumer the function applied to each onNext item 867 * @return a CompletableFuture that is completed normally 868 * when the publisher signals onComplete, and exceptionally 869 * upon any error or cancellation 870 * @throws NullPointerException if consumer is null 871 */ 872 public CompletableFuture<Void> consume(Consumer<? super T> consumer) { 873 if (consumer == null) 874 throw new NullPointerException(); 875 CompletableFuture<Void> status = new CompletableFuture<>(); 876 subscribe(new ConsumerSubscriber<T>(status, consumer)); 877 return status; 878 } 879 880 /** Subscriber for method consume */ 881 static final class ConsumerSubscriber<T> implements Subscriber<T> { 882 final CompletableFuture<Void> status; 883 final Consumer<? super T> consumer; 884 Subscription subscription; 885 ConsumerSubscriber(CompletableFuture<Void> status, 886 Consumer<? super T> consumer) { 887 this.status = status; this.consumer = consumer; 888 } 889 public final void onSubscribe(Subscription subscription) { 890 this.subscription = subscription; 891 status.whenComplete((v, e) -> subscription.cancel()); 892 if (!status.isDone()) 893 subscription.request(Long.MAX_VALUE); 894 } 895 public final void onError(Throwable ex) { 896 status.completeExceptionally(ex); 897 } 898 public final void onComplete() { 899 status.complete(null); 900 } 901 public final void onNext(T item) { 902 try { 903 consumer.accept(item); 904 } catch (Throwable ex) { 905 subscription.cancel(); 906 status.completeExceptionally(ex); 907 } 908 } 909 } 910 911 /** 912 * A task for consuming buffer items and signals, created and 913 * executed whenever they become available. A task consumes as 914 * many items/signals as possible before terminating, at which 915 * point another task is created when needed. The dual Runnable 916 * and ForkJoinTask declaration saves overhead when executed by 917 * ForkJoinPools, without impacting other kinds of Executors. 918 */ 919 @SuppressWarnings("serial") 920 static final class ConsumerTask<T> extends ForkJoinTask<Void> 921 implements Runnable, CompletableFuture.AsynchronousCompletionTask { 922 final BufferedSubscription<T> consumer; 923 ConsumerTask(BufferedSubscription<T> consumer) { 924 this.consumer = consumer; 925 } 926 public final Void getRawResult() { return null; } 927 public final void setRawResult(Void v) {} 928 public final boolean exec() { consumer.consume(); return false; } 929 public final void run() { consumer.consume(); } 930 } 931 932 /** 933 * A resizable array-based ring buffer with integrated control to 934 * start a consumer task whenever items are available. The buffer 935 * algorithm is specialized for the case of at most one concurrent 936 * producer and consumer, and power of two buffer sizes. It relies 937 * primarily on atomic operations (CAS or getAndSet) at the next 938 * array slot to put or take an element, at the "tail" and "head" 939 * indices written only by the producer and consumer respectively. 940 * 941 * We ensure internally that there is at most one active consumer 942 * task at any given time. The publisher guarantees a single 943 * producer via its lock. Sync among producers and consumers 944 * relies on volatile fields "ctl", "demand", and "waiting" (along 945 * with element access). Other variables are accessed in plain 946 * mode, relying on outer ordering and exclusion, and/or enclosing 947 * them within other volatile accesses. Some atomic operations are 948 * avoided by tracking single threaded ownership by producers (in 949 * the style of biased locking). 950 * 951 * Execution control and protocol state are managed using field 952 * "ctl". Methods to subscribe, close, request, and cancel set 953 * ctl bits (mostly using atomic boolean method getAndBitwiseOr), 954 * and ensure that a task is running. (The corresponding consumer 955 * side actions are in method consume.) To avoid starting a new 956 * task on each action, ctl also includes a keep-alive bit 957 * (ACTIVE) that is refreshed if needed on producer actions. 958 * (Maintaining agreement about keep-alives requires most atomic 959 * updates to be full SC/Volatile strength, which is still much 960 * cheaper than using one task per item.) Error signals 961 * additionally null out items and/or fields to reduce termination 962 * latency. The cancel() method is supported by treating as ERROR 963 * but suppressing onError signal. 964 * 965 * Support for blocking also exploits the fact that there is only 966 * one possible waiter. ManagedBlocker-compatible control fields 967 * are placed in this class itself rather than in wait-nodes. 968 * Blocking control relies on the "waiting" and "waiter" 969 * fields. Producers set them before trying to block. Signalling 970 * unparks and clears fields. If the producer and/or consumer are 971 * using a ForkJoinPool, the producer attempts to help run 972 * consumer tasks via ForkJoinPool.helpAsyncBlocker before 973 * blocking. 974 * 975 * Usages of this class may encounter any of several forms of 976 * memory contention. We try to ameliorate across them without 977 * unduly impacting footprints in low-contention usages where it 978 * isn't needed. Buffer arrays start out small and grow only as 979 * needed. The class uses @Contended and heuristic field 980 * declaration ordering to reduce false-sharing memory contention 981 * across instances of BufferedSubscription (as in, multiple 982 * subscribers per publisher). We additionally segregate some 983 * fields that would otherwise nearly always encounter cache line 984 * contention among producers and consumers. To reduce contention 985 * across time (vs space), consumers only periodically update 986 * other fields (see method takeItems), at the expense of possibly 987 * staler reporting of lags and demand (bounded at 12.5% == 1/8 988 * capacity) and possibly more atomic operations. 989 * 990 * Other forms of imbalance and slowdowns can occur during startup 991 * when producer and consumer methods are compiled and/or memory 992 * is allocated at different rates. This is ameliorated by 993 * artificially subdividing some consumer methods, including 994 * isolation of all subscriber callbacks. This code also includes 995 * typical power-of-two array screening idioms to avoid compilers 996 * generating traps, along with the usual SSA-based inline 997 * assignment coding style. Also, all methods and fields have 998 * default visibility to simplify usage by callers. 999 */ 1000 @SuppressWarnings("serial") 1001 @jdk.internal.vm.annotation.Contended 1002 static final class BufferedSubscription<T> 1003 implements Subscription, ForkJoinPool.ManagedBlocker { 1004 long timeout; // Long.MAX_VALUE if untimed wait 1005 int head; // next position to take 1006 int tail; // next position to put 1007 final int maxCapacity; // max buffer size 1008 volatile int ctl; // atomic run state flags 1009 Object[] array; // buffer 1010 final Subscriber<? super T> subscriber; 1011 final BiConsumer<? super Subscriber<? super T>, ? super Throwable> onNextHandler; 1012 Executor executor; // null on error 1013 Thread waiter; // blocked producer thread 1014 Throwable pendingError; // holds until onError issued 1015 BufferedSubscription<T> next; // used only by publisher 1016 BufferedSubscription<T> nextRetry; // used only by publisher 1017 1018 @jdk.internal.vm.annotation.Contended("c") // segregate 1019 volatile long demand; // # unfilled requests 1020 @jdk.internal.vm.annotation.Contended("c") 1021 volatile int waiting; // nonzero if producer blocked 1022 1023 // ctl bit values 1024 static final int CLOSED = 0x01; // if set, other bits ignored 1025 static final int ACTIVE = 0x02; // keep-alive for consumer task 1026 static final int REQS = 0x04; // (possibly) nonzero demand 1027 static final int ERROR = 0x08; // issues onError when noticed 1028 static final int COMPLETE = 0x10; // issues onComplete when done 1029 static final int RUN = 0x20; // task is or will be running 1030 static final int OPEN = 0x40; // true after subscribe 1031 1032 static final long INTERRUPTED = -1L; // timeout vs interrupt sentinel 1033 1034 BufferedSubscription(Subscriber<? super T> subscriber, 1035 Executor executor, 1036 BiConsumer<? super Subscriber<? super T>, 1037 ? super Throwable> onNextHandler, 1038 Object[] array, 1039 int maxBufferCapacity) { 1040 this.subscriber = subscriber; 1041 this.executor = executor; 1042 this.onNextHandler = onNextHandler; 1043 this.array = array; 1044 this.maxCapacity = maxBufferCapacity; 1045 } 1046 1047 // Wrappers for some VarHandle methods 1048 1049 final boolean weakCasCtl(int cmp, int val) { 1050 return CTL.weakCompareAndSet(this, cmp, val); 1051 } 1052 1053 final int getAndBitwiseOrCtl(int bits) { 1054 return (int)CTL.getAndBitwiseOr(this, bits); 1055 } 1056 1057 final long subtractDemand(int k) { 1058 long n = (long)(-k); 1059 return n + (long)DEMAND.getAndAdd(this, n); 1060 } 1061 1062 final boolean casDemand(long cmp, long val) { 1063 return DEMAND.compareAndSet(this, cmp, val); 1064 } 1065 1066 // Utilities used by SubmissionPublisher 1067 1068 /** 1069 * Returns true if closed (consumer task may still be running). 1070 */ 1071 final boolean isClosed() { 1072 return (ctl & CLOSED) != 0; 1073 } 1074 1075 /** 1076 * Returns estimated number of buffered items, or negative if 1077 * closed. 1078 */ 1079 final int estimateLag() { 1080 int c = ctl, n = tail - head; 1081 return ((c & CLOSED) != 0) ? -1 : (n < 0) ? 0 : n; 1082 } 1083 1084 // Methods for submitting items 1085 1086 /** 1087 * Tries to add item and start consumer task if necessary. 1088 * @return negative if closed, 0 if saturated, else estimated lag 1089 */ 1090 final int offer(T item, boolean unowned) { 1091 Object[] a; 1092 int stat = 0, cap = ((a = array) == null) ? 0 : a.length; 1093 int t = tail, i = t & (cap - 1), n = t + 1 - head; 1094 if (cap > 0) { 1095 boolean added; 1096 if (n >= cap && cap < maxCapacity) // resize 1097 added = growAndoffer(item, a, t); 1098 else if (n >= cap || unowned) // need volatile CAS 1099 added = QA.compareAndSet(a, i, null, item); 1100 else { // can use release mode 1101 QA.setRelease(a, i, item); 1102 added = true; 1103 } 1104 if (added) { 1105 tail = t + 1; 1106 stat = n; 1107 } 1108 } 1109 return startOnOffer(stat); 1110 } 1111 1112 /** 1113 * Tries to expand buffer and add item, returning true on 1114 * success. Currently fails only if out of memory. 1115 */ 1116 final boolean growAndoffer(T item, Object[] a, int t) { 1117 int cap = 0, newCap = 0; 1118 Object[] newArray = null; 1119 if (a != null && (cap = a.length) > 0 && (newCap = cap << 1) > 0) { 1120 try { 1121 newArray = new Object[newCap]; 1122 } catch (OutOfMemoryError ex) { 1123 } 1124 } 1125 if (newArray == null) 1126 return false; 1127 else { // take and move items 1128 int newMask = newCap - 1; 1129 newArray[t-- & newMask] = item; 1130 for (int mask = cap - 1, k = mask; k >= 0; --k) { 1131 Object x = QA.getAndSet(a, t & mask, null); 1132 if (x == null) 1133 break; // already consumed 1134 else 1135 newArray[t-- & newMask] = x; 1136 } 1137 array = newArray; 1138 VarHandle.releaseFence(); // release array and slots 1139 return true; 1140 } 1141 } 1142 1143 /** 1144 * Version of offer for retries (no resize or bias) 1145 */ 1146 final int retryOffer(T item) { 1147 Object[] a; 1148 int stat = 0, t = tail, h = head, cap; 1149 if ((a = array) != null && (cap = a.length) > 0 && 1150 QA.compareAndSet(a, (cap - 1) & t, null, item)) 1151 stat = (tail = t + 1) - h; 1152 return startOnOffer(stat); 1153 } 1154 1155 /** 1156 * Tries to start consumer task after offer. 1157 * @return negative if now closed, else argument 1158 */ 1159 final int startOnOffer(int stat) { 1160 int c; // start or keep alive if requests exist and not active 1161 if (((c = ctl) & (REQS | ACTIVE)) == REQS && 1162 ((c = getAndBitwiseOrCtl(RUN | ACTIVE)) & (RUN | CLOSED)) == 0) 1163 tryStart(); 1164 else if ((c & CLOSED) != 0) 1165 stat = -1; 1166 return stat; 1167 } 1168 1169 /** 1170 * Tries to start consumer task. Sets error state on failure. 1171 */ 1172 final void tryStart() { 1173 try { 1174 Executor e; 1175 ConsumerTask<T> task = new ConsumerTask<T>(this); 1176 if ((e = executor) != null) // skip if disabled on error 1177 e.execute(task); 1178 } catch (RuntimeException | Error ex) { 1179 getAndBitwiseOrCtl(ERROR | CLOSED); 1180 throw ex; 1181 } 1182 } 1183 1184 // Signals to consumer tasks 1185 1186 /** 1187 * Sets the given control bits, starting task if not running or closed. 1188 * @param bits state bits, assumed to include RUN but not CLOSED 1189 */ 1190 final void startOnSignal(int bits) { 1191 if ((ctl & bits) != bits && 1192 (getAndBitwiseOrCtl(bits) & (RUN | CLOSED)) == 0) 1193 tryStart(); 1194 } 1195 1196 final void onSubscribe() { 1197 startOnSignal(RUN | ACTIVE); 1198 } 1199 1200 final void onComplete() { 1201 startOnSignal(RUN | ACTIVE | COMPLETE); 1202 } 1203 1204 final void onError(Throwable ex) { 1205 int c; Object[] a; // to null out buffer on async error 1206 if (ex != null) 1207 pendingError = ex; // races are OK 1208 if (((c = getAndBitwiseOrCtl(ERROR | RUN | ACTIVE)) & CLOSED) == 0) { 1209 if ((c & RUN) == 0) 1210 tryStart(); 1211 else if ((a = array) != null) 1212 Arrays.fill(a, null); 1213 } 1214 } 1215 1216 public final void cancel() { 1217 onError(null); 1218 } 1219 1220 public final void request(long n) { 1221 if (n > 0L) { 1222 for (;;) { 1223 long p = demand, d = p + n; // saturate 1224 if (casDemand(p, d < p ? Long.MAX_VALUE : d)) 1225 break; 1226 } 1227 startOnSignal(RUN | ACTIVE | REQS); 1228 } 1229 else 1230 onError(new IllegalArgumentException( 1231 "non-positive subscription request")); 1232 } 1233 1234 // Consumer task actions 1235 1236 /** 1237 * Consumer loop, called from ConsumerTask, or indirectly when 1238 * helping during submit. 1239 */ 1240 final void consume() { 1241 Subscriber<? super T> s; 1242 if ((s = subscriber) != null) { // hoist checks 1243 subscribeOnOpen(s); 1244 long d = demand; 1245 for (int h = head, t = tail;;) { 1246 int c, taken; boolean empty; 1247 if (((c = ctl) & ERROR) != 0) { 1248 closeOnError(s, null); 1249 break; 1250 } 1251 else if ((taken = takeItems(s, d, h)) > 0) { 1252 head = h += taken; 1253 d = subtractDemand(taken); 1254 } 1255 else if ((empty = (t == h)) && (c & COMPLETE) != 0) { 1256 closeOnComplete(s); // end of stream 1257 break; 1258 } 1259 else if ((d = demand) == 0L && (c & REQS) != 0) 1260 weakCasCtl(c, c & ~REQS); // exhausted demand 1261 else if (d != 0L && (c & REQS) == 0) 1262 weakCasCtl(c, c | REQS); // new demand 1263 else if (t == (t = tail) && (empty || d == 0L)) { 1264 int bit = ((c & ACTIVE) != 0) ? ACTIVE : RUN; 1265 if (weakCasCtl(c, c & ~bit) && bit == RUN) 1266 break; // un-keep-alive or exit 1267 } 1268 } 1269 } 1270 } 1271 1272 /** 1273 * Consumes some items until unavailable or bound or error. 1274 * 1275 * @param s subscriber 1276 * @param d current demand 1277 * @param h current head 1278 * @return number taken 1279 */ 1280 final int takeItems(Subscriber<? super T> s, long d, int h) { 1281 Object[] a; 1282 int k = 0, cap; 1283 if ((a = array) != null && (cap = a.length) > 0) { 1284 int m = cap - 1, b = (m >>> 3) + 1; // min(1, cap/8) 1285 int n = (d < (long)b) ? (int)d : b; 1286 for (; k < n; ++h, ++k) { 1287 Object x = QA.getAndSet(a, h & m, null); 1288 if (waiting != 0) 1289 signalWaiter(); 1290 if (x == null) 1291 break; 1292 else if (!consumeNext(s, x)) 1293 break; 1294 } 1295 } 1296 return k; 1297 } 1298 1299 final boolean consumeNext(Subscriber<? super T> s, Object x) { 1300 try { 1301 @SuppressWarnings("unchecked") T y = (T) x; 1302 if (s != null) 1303 s.onNext(y); 1304 return true; 1305 } catch (Throwable ex) { 1306 handleOnNext(s, ex); 1307 return false; 1308 } 1309 } 1310 1311 /** 1312 * Processes exception in Subscriber.onNext. 1313 */ 1314 final void handleOnNext(Subscriber<? super T> s, Throwable ex) { 1315 BiConsumer<? super Subscriber<? super T>, ? super Throwable> h; 1316 try { 1317 if ((h = onNextHandler) != null) 1318 h.accept(s, ex); 1319 } catch (Throwable ignore) { 1320 } 1321 closeOnError(s, ex); 1322 } 1323 1324 /** 1325 * Issues subscriber.onSubscribe if this is first signal. 1326 */ 1327 final void subscribeOnOpen(Subscriber<? super T> s) { 1328 if ((ctl & OPEN) == 0 && (getAndBitwiseOrCtl(OPEN) & OPEN) == 0) 1329 consumeSubscribe(s); 1330 } 1331 1332 final void consumeSubscribe(Subscriber<? super T> s) { 1333 try { 1334 if (s != null) // ignore if disabled 1335 s.onSubscribe(this); 1336 } catch (Throwable ex) { 1337 closeOnError(s, ex); 1338 } 1339 } 1340 1341 /** 1342 * Issues subscriber.onComplete unless already closed. 1343 */ 1344 final void closeOnComplete(Subscriber<? super T> s) { 1345 if ((getAndBitwiseOrCtl(CLOSED) & CLOSED) == 0) 1346 consumeComplete(s); 1347 } 1348 1349 final void consumeComplete(Subscriber<? super T> s) { 1350 try { 1351 if (s != null) 1352 s.onComplete(); 1353 } catch (Throwable ignore) { 1354 } 1355 } 1356 1357 /** 1358 * Issues subscriber.onError, and unblocks producer if needed. 1359 */ 1360 final void closeOnError(Subscriber<? super T> s, Throwable ex) { 1361 if ((getAndBitwiseOrCtl(ERROR | CLOSED) & CLOSED) == 0) { 1362 if (ex == null) 1363 ex = pendingError; 1364 pendingError = null; // detach 1365 executor = null; // suppress racing start calls 1366 signalWaiter(); 1367 consumeError(s, ex); 1368 } 1369 } 1370 1371 final void consumeError(Subscriber<? super T> s, Throwable ex) { 1372 try { 1373 if (ex != null && s != null) 1374 s.onError(ex); 1375 } catch (Throwable ignore) { 1376 } 1377 } 1378 1379 // Blocking support 1380 1381 /** 1382 * Unblocks waiting producer. 1383 */ 1384 final void signalWaiter() { 1385 Thread w; 1386 waiting = 0; 1387 if ((w = waiter) != null) 1388 LockSupport.unpark(w); 1389 } 1390 1391 /** 1392 * Returns true if closed or space available. 1393 * For ManagedBlocker. 1394 */ 1395 public final boolean isReleasable() { 1396 Object[] a; int cap; 1397 return ((ctl & CLOSED) != 0 || 1398 ((a = array) != null && (cap = a.length) > 0 && 1399 QA.getAcquire(a, (cap - 1) & tail) == null)); 1400 } 1401 1402 /** 1403 * Helps or blocks until timeout, closed, or space available. 1404 */ 1405 final void awaitSpace(long nanos) { 1406 if (!isReleasable()) { 1407 ForkJoinPool.helpAsyncBlocker(executor, this); 1408 if (!isReleasable()) { 1409 timeout = nanos; 1410 try { 1411 ForkJoinPool.managedBlock(this); 1412 } catch (InterruptedException ie) { 1413 timeout = INTERRUPTED; 1414 } 1415 if (timeout == INTERRUPTED) 1416 Thread.currentThread().interrupt(); 1417 } 1418 } 1419 } 1420 1421 /** 1422 * Blocks until closed, space available or timeout. 1423 * For ManagedBlocker. 1424 */ 1425 public final boolean block() { 1426 long nanos = timeout; 1427 boolean timed = (nanos < Long.MAX_VALUE); 1428 long deadline = timed ? System.nanoTime() + nanos : 0L; 1429 while (!isReleasable()) { 1430 if (Thread.interrupted()) { 1431 timeout = INTERRUPTED; 1432 if (timed) 1433 break; 1434 } 1435 else if (timed && (nanos = deadline - System.nanoTime()) <= 0L) 1436 break; 1437 else if (waiter == null) 1438 waiter = Thread.currentThread(); 1439 else if (waiting == 0) 1440 waiting = 1; 1441 else if (timed) 1442 LockSupport.parkNanos(this, nanos); 1443 else 1444 LockSupport.park(this); 1445 } 1446 waiter = null; 1447 waiting = 0; 1448 return true; 1449 } 1450 1451 // VarHandle mechanics 1452 static final VarHandle CTL; 1453 static final VarHandle DEMAND; 1454 static final VarHandle QA; 1455 1456 static { 1457 try { 1458 MethodHandles.Lookup l = MethodHandles.lookup(); 1459 CTL = l.findVarHandle(BufferedSubscription.class, "ctl", 1460 int.class); 1461 DEMAND = l.findVarHandle(BufferedSubscription.class, "demand", 1462 long.class); 1463 QA = MethodHandles.arrayElementVarHandle(Object[].class); 1464 } catch (ReflectiveOperationException e) { 1465 throw new Error(e); 1466 } 1467 1468 // Reduce the risk of rare disastrous classloading in first call to 1469 // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773 1470 Class<?> ensureLoaded = LockSupport.class; 1471 } 1472 } 1473 }