ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Flow.java
Revision: 1.26
Committed: Sun Sep 13 11:41:23 2015 UTC (8 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.25: +8 -10 lines
Log Message:
incorporate suggested doc improvements

File Contents

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