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 /**
  39  * Interrelated interfaces and static methods for establishing
  40  * flow-controlled components in which {@link Publisher Publishers}
  41  * produce items consumed by one or more {@link Subscriber
  42  * Subscribers}, each managed by a {@link Subscription
  43  * Subscription}.
  44  *
  45  * <p>These interfaces correspond to the <a
  46  * href="http://www.reactive-streams.org/"> reactive-streams</a>
  47  * specification.  They apply in both concurrent and distributed
  48  * asynchronous settings: All (seven) methods are defined in {@code
  49  * void} "one-way" message style. Communication relies on a simple form
  50  * of flow control (method {@link Subscription#request}) that can be
  51  * used to avoid resource management problems that may otherwise occur
  52  * in "push" based systems.
  53  *
  54  * <p><b>Examples.</b> A {@link Publisher} usually defines its own
  55  * {@link Subscription} implementation; constructing one in method
  56  * {@code subscribe} and issuing it to the calling {@link
  57  * Subscriber}. It publishes items to the subscriber asynchronously,
  58  * normally using an {@link Executor}.  For example, here is a very
  59  * simple publisher that only issues (when requested) a single {@code
  60  * TRUE} item to a single subscriber.  Because the subscriber receives
  61  * only a single item, this class does not use buffering and ordering
  62  * control required in most implementations (for example {@link
  63  * SubmissionPublisher}).
  64  *
  65  * <pre> {@code
  66  * class OneShotPublisher implements Publisher<Boolean> {
  67  *   private final ExecutorService executor = ForkJoinPool.commonPool(); // daemon-based
  68  *   private boolean subscribed; // true after first subscribe
  69  *   public synchronized void subscribe(Subscriber<? super Boolean> subscriber) {
  70  *     if (subscribed)
  71  *        subscriber.onError(new IllegalStateException()); // only one allowed
  72  *     else {
  73  *       subscribed = true;
  74  *       subscriber.onSubscribe(new OneShotSubscription(subscriber, executor));
  75  *     }
  76  *   }
  77  *   static class OneShotSubscription implements Subscription {
  78  *     private final Subscriber<? super Boolean> subscriber;
  79  *     private final ExecutorService executor;
  80  *     private Future<?> future; // to allow cancellation
  81  *     private boolean completed;
  82  *     OneShotSubscription(Subscriber<? super Boolean> subscriber,
  83  *                         ExecutorService executor) {
  84  *       this.subscriber = subscriber;
  85  *       this.executor = executor;
  86  *     }
  87  *     public synchronized void request(long n) {
  88  *       if (n != 0 && !completed) {
  89  *         completed = true;
  90  *         if (n < 0) {
  91  *           IllegalArgumentException ex = new IllegalArgumentException();
  92  *           executor.execute(() -> subscriber.onError(ex));
  93  *         } else {
  94  *           future = executor.submit(() -> {
  95  *             subscriber.onNext(Boolean.TRUE);
  96  *             subscriber.onComplete();
  97  *           });
  98  *         }
  99  *       }
 100  *     }
 101  *     public synchronized void cancel() {
 102  *       completed = true;
 103  *       if (future != null) future.cancel(false);
 104  *     }
 105  *   }
 106  * }}</pre>
 107  *
 108  * <p>A {@link Subscriber} arranges that items be requested and
 109  * processed.  Items (invocations of {@link Subscriber#onNext}) are
 110  * not issued unless requested, but multiple items may be requested.
 111  * Many Subscriber implementations can arrange this in the style of
 112  * the following example, where a buffer size of 1 single-steps, and
 113  * larger sizes usually allow for more efficient overlapped processing
 114  * with less communication; for example with a value of 64, this keeps
 115  * total outstanding requests between 32 and 64.
 116  * Because Subscriber method invocations for a given {@link
 117  * Subscription} are strictly ordered, there is no need for these
 118  * methods to use locks or volatiles unless a Subscriber maintains
 119  * multiple Subscriptions (in which case it is better to instead
 120  * define multiple Subscribers, each with its own Subscription).
 121  *
 122  * <pre> {@code
 123  * class SampleSubscriber<T> implements Subscriber<T> {
 124  *   final Consumer<? super T> consumer;
 125  *   Subscription subscription;
 126  *   final long bufferSize;
 127  *   long count;
 128  *   SampleSubscriber(long bufferSize, Consumer<? super T> consumer) {
 129  *     this.bufferSize = bufferSize;
 130  *     this.consumer = consumer;
 131  *   }
 132  *   public void onSubscribe(Subscription subscription) {
 133  *     long initialRequestSize = bufferSize;
 134  *     count = bufferSize - bufferSize / 2; // re-request when half consumed
 135  *     (this.subscription = subscription).request(initialRequestSize);
 136  *   }
 137  *   public void onNext(T item) {
 138  *     if (--count <= 0)
 139  *       subscription.request(count = bufferSize - bufferSize / 2);
 140  *     consumer.accept(item);
 141  *   }
 142  *   public void onError(Throwable ex) { ex.printStackTrace(); }
 143  *   public void onComplete() {}
 144  * }}</pre>
 145  *
 146  * <p>The default value of {@link #defaultBufferSize} may provide a
 147  * useful starting point for choosing request sizes and capacities in
 148  * Flow components based on expected rates, resources, and usages.
 149  * Or, when flow control is never needed, a subscriber may initially
 150  * request an effectively unbounded number of items, as in:
 151  *
 152  * <pre> {@code
 153  * class UnboundedSubscriber<T> implements Subscriber<T> {
 154  *   public void onSubscribe(Subscription subscription) {
 155  *     subscription.request(Long.MAX_VALUE); // effectively unbounded
 156  *   }
 157  *   public void onNext(T item) { use(item); }
 158  *   public void onError(Throwable ex) { ex.printStackTrace(); }
 159  *   public void onComplete() {}
 160  *   void use(T item) { ... }
 161  * }}</pre>
 162  *
 163  * @author Doug Lea
 164  * @since 1.9
 165  */
 166 public final class Flow {
 167 
 168     private Flow() {} // uninstantiable
 169 
 170     /**
 171      * A producer of items (and related control messages) received by
 172      * Subscribers.  Each current {@link Subscriber} receives the same
 173      * items (via method {@code onNext}) in the same order, unless
 174      * drops or errors are encountered. If a Publisher encounters an
 175      * error that does not allow items to be issued to a Subscriber,
 176      * that Subscriber receives {@code onError}, and then receives no
 177      * further messages.  Otherwise, when it is known that no further
 178      * messages will be issued to it, a subscriber receives {@code
 179      * onComplete}.  Publishers ensure that Subscriber method
 180      * invocations for each subscription are strictly ordered in <a
 181      * href="package-summary.html#MemoryVisibility"><i>happens-before</i></a>
 182      * order.
 183      *
 184      * <p>Publishers may vary in policy about whether drops (failures
 185      * to issue an item because of resource limitations) are treated
 186      * as unrecoverable errors.  Publishers may also vary about
 187      * whether Subscribers receive items that were produced or
 188      * available before they subscribed.
 189      *
 190      * @param <T> the published item type
 191      */
 192     @FunctionalInterface
 193     public static interface Publisher<T> {
 194         /**
 195          * Adds the given Subscriber if possible.  If already
 196          * subscribed, or the attempt to subscribe fails due to policy
 197          * violations or errors, the Subscriber's {@code onError}
 198          * method is invoked with an {@link IllegalStateException}.
 199          * Otherwise, the Subscriber's {@code onSubscribe} method is
 200          * invoked with a new {@link Subscription}.  Subscribers may
 201          * enable receiving items by invoking the {@code request}
 202          * method of this Subscription, and may unsubscribe by
 203          * invoking its {@code cancel} method.
 204          *
 205          * @param subscriber the subscriber
 206          * @throws NullPointerException if subscriber is null
 207          */
 208         public void subscribe(Subscriber<? super T> subscriber);
 209     }
 210 
 211     /**
 212      * A receiver of messages.  The methods in this interface are
 213      * invoked in strict sequential order for each {@link
 214      * Subscription}.
 215      *
 216      * @param <T> the subscribed item type
 217      */
 218     public static interface Subscriber<T> {
 219         /**
 220          * Method invoked prior to invoking any other Subscriber
 221          * methods for the given Subscription. If this method throws
 222          * an exception, resulting behavior is not guaranteed, but may
 223          * cause the Subscription not to be established or to be cancelled.
 224          *
 225          * <p>Typically, implementations of this method invoke {@code
 226          * subscription.request} to enable receiving items.
 227          *
 228          * @param subscription a new subscription
 229          */
 230         public void onSubscribe(Subscription subscription);
 231 
 232         /**
 233          * Method invoked with a Subscription's next item.  If this
 234          * method throws an exception, resulting behavior is not
 235          * guaranteed, but may cause the Subscription to be cancelled.
 236          *
 237          * @param item the item
 238          */
 239         public void onNext(T item);
 240 
 241         /**
 242          * Method invoked upon an unrecoverable error encountered by a
 243          * Publisher or Subscription, after which no other Subscriber
 244          * methods are invoked by the Subscription.  If this method
 245          * itself throws an exception, resulting behavior is
 246          * undefined.
 247          *
 248          * @param throwable the exception
 249          */
 250         public void onError(Throwable throwable);
 251 
 252         /**
 253          * Method invoked when it is known that no additional
 254          * Subscriber method invocations will occur for a Subscription
 255          * that is not already terminated by error, after which no
 256          * other Subscriber methods are invoked by the Subscription.
 257          * If this method throws an exception, resulting behavior is
 258          * undefined.
 259          */
 260         public void onComplete();
 261     }
 262 
 263     /**
 264      * Message control linking a {@link Publisher} and {@link
 265      * Subscriber}.  Subscribers receive items only when requested,
 266      * and may cancel at any time. The methods in this interface are
 267      * intended to be invoked only by their Subscribers; usages in
 268      * other contexts have undefined effects.
 269      */
 270     public static interface Subscription {
 271         /**
 272          * Adds the given number {@code n} of items to the current
 273          * unfulfilled demand for this subscription.  If {@code n} is
 274          * negative, the Subscriber will receive an {@code onError}
 275          * signal with an {@link IllegalArgumentException} argument.
 276          * Otherwise, the Subscriber will receive up to {@code n}
 277          * additional {@code onNext} invocations (or fewer if
 278          * terminated).
 279          *
 280          * @param n the increment of demand; a value of {@code
 281          * Long.MAX_VALUE} may be considered as effectively unbounded
 282          */
 283         public void request(long n);
 284 
 285         /**
 286          * Causes the Subscriber to (eventually) stop receiving
 287          * messages.  Implementation is best-effort -- additional
 288          * messages may be received after invoking this method.
 289          * A cancelled subscription need not ever receive an
 290          * {@code onComplete} or {@code onError} signal.
 291          */
 292         public void cancel();
 293     }
 294 
 295     /**
 296      * A component that acts as both a Subscriber and Publisher.
 297      *
 298      * @param <T> the subscribed item type
 299      * @param <R> the published item type
 300      */
 301     public static interface Processor<T,R> extends Subscriber<T>, Publisher<R> {
 302     }
 303 
 304     static final int DEFAULT_BUFFER_SIZE = 256;
 305 
 306     /**
 307      * Returns a default value for Publisher or Subscriber buffering,
 308      * that may be used in the absence of other constraints.
 309      *
 310      * @implNote
 311      * The current value returned is 256.
 312      *
 313      * @return the buffer size value
 314      */
 315     public static int defaultBufferSize() {
 316         return DEFAULT_BUFFER_SIZE;
 317     }
 318 
 319 }