ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Flow.java
Revision: 1.20
Committed: Sat Jan 24 18:50:40 2015 UTC (9 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.19: +1 -1 lines
Log Message:
readability

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.17 * final ExecutorService executor = ForkJoinPool.commonPool(); // daemon-based
44 dl 1.16 * boolean subscribed = false; // true after first subscribe
45     * 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     * final Subscriber<? super Boolean> subscriber;
55 dl 1.17 * final ExecutorService executor;
56     * Future<?> future; // to allow cancellation
57 dl 1.16 * boolean completed = false;
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.17 * future = executor.submit(() -> {
67 dl 1.16 * if (n < 0)
68     * subscriber.onError(new IllegalArgumentException());
69     * else {
70     * subscriber.onNext(Boolean.TRUE);
71     * subscriber.onComplete();
72     * }});
73 dl 1.10 * }
74     * }
75 dl 1.15 * public synchronized void cancel() {
76 dl 1.17 * completed = true;
77     * if (future != null) future.cancel(false);
78 dl 1.15 * }
79 dl 1.10 * }
80     * }}</pre>
81     *
82 jsr166 1.13 * <p>A {@link Subscriber} arranges that items be requested and
83 dl 1.10 * processed. Items (invocations of {@link Subscriber#onNext}) are
84     * not issued unless requested, but multiple items may be requested.
85     * Many Subscriber implementations can arrange this in the style of
86     * the following example, where a buffer size of 1 single-steps, and
87     * larger sizes usually allow for more efficient overlapped processing
88     * with less communication; for example with a value of 64, this keeps
89     * total outstanding requests between 32 and 64. (See also {@link
90     * #consume(long, Publisher, Consumer)} that automates a common case.)
91 dl 1.14 * Because Subscriber method invocations for a given {@link
92     * Subscription} are strictly ordered, there is no need for these
93     * methods to use locks or volatiles unless a Subscriber maintains
94     * multiple Subscriptions (in which case it is better to instead
95     * define multiple Subscribers, each with its own Subscription).
96 dl 1.10 *
97     * <pre> {@code
98     * class SampleSubscriber<T> implements Subscriber<T> {
99     * final Consumer<? super T> consumer;
100     * Subscription subscription;
101     * final long bufferSize;
102     * long count;
103     * SampleSubscriber(long bufferSize, Consumer<? super T> consumer) {
104     * this.bufferSize = bufferSize;
105     * this.consumer = consumer;
106     * }
107     * public void onSubscribe(Subscription subscription) {
108     * (this.subscription = subscription).request(bufferSize);
109     * count = bufferSize - bufferSize / 2; // re-request when half consumed
110     * }
111     * public void onNext(T item) {
112     * if (--count <= 0)
113     * subscription.request(count = bufferSize - bufferSize / 2);
114     * consumer.accept(item);
115     * }
116     * public void onError(Throwable ex) { ex.printStackTrace(); }
117     * public void onComplete() {}
118     * }}</pre>
119 dl 1.1 *
120 dl 1.18 * <p>The default value of {@link #defaultBufferSize} may provide a
121     * useful starting point for choosing request sizes and capacities in
122     * Flow components based on expected rates, resources, and usages.
123     * Or, when flow control is known to be always inapplicable, a
124     * subscriber may initially request an effectively unbounded number of
125     * items, as in:
126 dl 1.12 *
127     * <pre> {@code
128     * class UnboundedSubscriber<T> implements Subscriber<T> {
129     * public void onSubscribe(Subscription subscription) {
130     * subscription.request(Long.MAX_VALUE); // effectively unbounded
131     * }
132     * public void onNext(T item) { use(item); }
133     * public void onError(Throwable ex) { ex.printStackTrace(); }
134     * public void onComplete() {}
135     * void use(T item) { ... }
136     * }}</pre>
137 jsr166 1.13 *
138 dl 1.1 * @author Doug Lea
139     * @since 1.9
140     */
141     public final class Flow {
142    
143     private Flow() {} // uninstantiable
144    
145     /**
146     * A producer of items (and related control messages) received by
147     * Subscribers. Each current {@link Subscriber} receives the same
148 dl 1.14 * items (via method {@code onNext}) in the same order, unless
149     * drops or errors are encountered. If a Publisher encounters an
150 dl 1.15 * error that does not allow items to be issued to a Subscriber,
151     * that Subscriber receives {@code onError}, and then receives no
152     * further messages. Otherwise, when it is known that no further
153     * messages will be issued to it, a subscriber receives {@code
154     * onComplete}. Publishers ensure that Subscriber method
155 dl 1.14 * invocations for each subscription are strictly ordered in <a
156     * href="package-summary.html#MemoryVisibility"><i>happens-before</i></a>
157     * order.
158     *
159 dl 1.15 * <p>Publishers may vary in policy about whether drops (failures
160     * to issue an item because of resource limitations) are treated
161     * as unrecoverable errors. Publishers may also vary about
162     * whether Subscribers receive items that were produced or
163     * available before they subscribed.
164 dl 1.1 *
165     * @param <T> the published item type
166     */
167     @FunctionalInterface
168     public static interface Publisher<T> {
169     /**
170     * Adds the given Subscriber if possible. If already
171     * subscribed, or the attempt to subscribe fails due to policy
172 dl 1.14 * violations or errors, the Subscriber's {@code onError}
173     * method is invoked with an {@link IllegalStateException}.
174     * Otherwise, the Subscriber's {@code onSubscribe} method is
175     * invoked with a new {@link Subscription}. Subscribers may
176     * enable receiving items by invoking the {@code request}
177     * method of this Subscription, and may unsubscribe by
178     * invoking its {@code cancel} method.
179 dl 1.1 *
180     * @param subscriber the subscriber
181     * @throws NullPointerException if subscriber is null
182     */
183     public void subscribe(Subscriber<? super T> subscriber);
184     }
185    
186     /**
187 dl 1.14 * A receiver of messages. The methods in this interface are
188     * invoked in strict sequential order for each {@link
189     * Subscription}.
190 dl 1.1 *
191     * @param <T> the subscribed item type
192     */
193     public static interface Subscriber<T> {
194     /**
195     * Method invoked prior to invoking any other Subscriber
196     * methods for the given Subscription. If this method throws
197     * an exception, resulting behavior is not guaranteed, but may
198     * cause the Subscription to be cancelled.
199     *
200 dl 1.15 * <p>Typically, implementations of this method invoke {@code
201     * subscription.request} to enable receiving items.
202 dl 1.1 *
203     * @param subscription a new subscription
204     */
205     public void onSubscribe(Subscription subscription);
206    
207     /**
208     * Method invoked with a Subscription's next item. If this
209     * method throws an exception, resulting behavior is not
210     * guaranteed, but may cause the Subscription to be cancelled.
211     *
212     * @param item the item
213     */
214     public void onNext(T item);
215    
216     /**
217     * Method invoked upon an unrecoverable error encountered by a
218     * Publisher or Subscription, after which no other Subscriber
219     * methods are invoked by the Subscription. If this method
220     * itself throws an exception, resulting behavior is
221     * undefined.
222     *
223     * @param throwable the exception
224     */
225     public void onError(Throwable throwable);
226    
227     /**
228 dl 1.15 * Method invoked when it is known that no additional
229     * Subscriber method invocations will occur for a Subscription
230     * that is not already terminated by error, after which no
231     * other Subscriber methods are invoked by the Subscription.
232     * If this method throws an exception, resulting behavior is
233 dl 1.14 * undefined.
234 dl 1.1 */
235     public void onComplete();
236     }
237    
238     /**
239 dl 1.14 * Message control linking a {@link Publisher} and {@link
240     * Subscriber}. Subscribers receive items only when requested,
241     * and may cancel at any time. The methods in this interface are
242     * intended to be invoked only by their Subscribers; usages in
243     * other contexts have undefined effects.
244 dl 1.1 */
245     public static interface Subscription {
246     /**
247     * Adds the given number {@code n} of items to the current
248     * unfulfilled demand for this subscription. If {@code n} is
249 dl 1.14 * negative, the Subscriber will receive an {@code onError}
250 jsr166 1.19 * signal with an {@link IllegalArgumentException} argument.
251     * Otherwise, the Subscriber will receive up to {@code n}
252     * additional {@code onNext} invocations (or fewer if
253     * terminated).
254 dl 1.1 *
255     * @param n the increment of demand; a value of {@code
256     * Long.MAX_VALUE} may be considered as effectively unbounded
257     */
258     public void request(long n);
259    
260     /**
261 dl 1.14 * Causes the Subscriber to (eventually) stop receiving
262 dl 1.15 * messages. Implementation is best-effort -- additional
263     * messages may be received after invoking this method. A
264     * cancelled subscription need not ever receive an {@code
265     * onComplete} signal.
266 dl 1.1 */
267     public void cancel();
268     }
269    
270     /**
271 jsr166 1.2 * A component that acts as both a Subscriber and Publisher.
272 dl 1.1 *
273 jsr166 1.2 * @param <T> the subscribed item type
274     * @param <R> the published item type
275     */
276 jsr166 1.5 public static interface Processor<T,R> extends Subscriber<T>, Publisher<R> {
277 dl 1.1 }
278    
279     // Support for static methods
280    
281 dl 1.18 static final int DEFAULT_BUFFER_SIZE = 256;
282    
283     /**
284     * Returns a default value for Publisher or Subscriber buffering,
285     * that may be used in the absence of other constraints.
286     *
287     * @implNote
288     * The current value returned is 256.
289     *
290     * @return the buffer size value
291     */
292     public static int defaultBufferSize() {
293     return DEFAULT_BUFFER_SIZE;
294     }
295 dl 1.1
296 jsr166 1.19 abstract static class CompletableSubscriber<T,U>
297     implements Subscriber<T>, Consumer<T>
298     {
299 dl 1.1 final CompletableFuture<U> status;
300     Subscription subscription;
301 dl 1.10 long requestSize;
302 jsr166 1.2 long count;
303 dl 1.10 CompletableSubscriber(long bufferSize, CompletableFuture<U> status) {
304 dl 1.1 this.status = status;
305 dl 1.10 this.requestSize = bufferSize;
306 dl 1.1 }
307     public final void onSubscribe(Subscription subscription) {
308     (this.subscription = subscription).request(requestSize);
309 dl 1.10 count = requestSize -= (requestSize >>> 1);
310 dl 1.1 }
311 jsr166 1.2 public final void onError(Throwable ex) {
312 dl 1.1 status.completeExceptionally(ex);
313     }
314     public void onNext(T item) {
315 dl 1.10 try {
316     if (--count <= 0)
317     subscription.request(count = requestSize);
318     accept(item);
319     } catch (Throwable ex) {
320     status.completeExceptionally(ex);
321 dl 1.1 }
322     }
323     }
324 jsr166 1.2
325 dl 1.1 static final class ConsumeSubscriber<T> extends CompletableSubscriber<T,Void> {
326     final Consumer<? super T> consumer;
327 dl 1.10 ConsumeSubscriber(long bufferSize,
328 dl 1.1 CompletableFuture<Void> status,
329     Consumer<? super T> consumer) {
330 dl 1.10 super(bufferSize, status);
331 dl 1.1 this.consumer = consumer;
332     }
333     public void accept(T item) { consumer.accept(item); }
334     public void onComplete() { status.complete(null); }
335     }
336    
337     /**
338     * Creates and subscribes a Subscriber that consumes all items
339     * from the given publisher using the given Consumer function, and
340 dl 1.10 * using the given bufferSize for buffering. Returns a
341 dl 1.1 * CompletableFuture that is completed normally when the publisher
342 dl 1.14 * signals {@code onComplete}, or completed exceptionally upon any
343     * error, including an exception thrown by the Consumer (in which
344     * case the subscription is cancelled if not already terminated).
345 dl 1.1 *
346 jsr166 1.4 * @param <T> the published item type
347 dl 1.10 * @param bufferSize the request size for subscriptions
348 dl 1.1 * @param publisher the publisher
349     * @param consumer the function applied to each onNext item
350     * @return a CompletableFuture that is completed normally
351     * when the publisher signals onComplete, and exceptionally
352 jsr166 1.7 * upon any error
353 dl 1.1 * @throws NullPointerException if publisher or consumer are null
354 dl 1.10 * @throws IllegalArgumentException if bufferSize not positive
355 dl 1.1 */
356     public static <T> CompletableFuture<Void> consume(
357 dl 1.10 long bufferSize, Publisher<T> publisher, Consumer<? super T> consumer) {
358     if (bufferSize <= 0L)
359     throw new IllegalArgumentException("bufferSize must be positive");
360 dl 1.1 if (publisher == null || consumer == null)
361     throw new NullPointerException();
362     CompletableFuture<Void> status = new CompletableFuture<>();
363     publisher.subscribe(new ConsumeSubscriber<T>(
364 dl 1.10 bufferSize, status, consumer));
365 dl 1.1 return status;
366     }
367    
368     /**
369     * Equivalent to {@link #consume(long, Publisher, Consumer)}
370 dl 1.18 * with {@link #defaultBufferSize}.
371 dl 1.1 *
372 jsr166 1.4 * @param <T> the published item type
373 dl 1.1 * @param publisher the publisher
374     * @param consumer the function applied to each onNext item
375     * @return a CompletableFuture that is completed normally
376     * when the publisher signals onComplete, and exceptionally
377 jsr166 1.7 * upon any error
378 dl 1.1 * @throws NullPointerException if publisher or consumer are null
379     */
380     public static <T> CompletableFuture<Void> consume(
381     Publisher<T> publisher, Consumer<? super T> consumer) {
382 dl 1.18 return consume(defaultBufferSize(), publisher, consumer);
383 dl 1.1 }
384    
385     /**
386     * Temporary implementation for Stream, collecting all items
387     * and then applying stream operation.
388     */
389     static final class StreamSubscriber<T,R> extends CompletableSubscriber<T,R> {
390     final Function<? super Stream<T>, ? extends R> fn;
391     final ArrayList<T> items;
392 dl 1.10 StreamSubscriber(long bufferSize,
393 dl 1.1 CompletableFuture<R> status,
394     Function<? super Stream<T>, ? extends R> fn) {
395 dl 1.10 super(bufferSize, status);
396 dl 1.1 this.fn = fn;
397     this.items = new ArrayList<T>();
398     }
399     public void accept(T item) { items.add(item); }
400     public void onComplete() { status.complete(fn.apply(items.stream())); }
401     }
402    
403     /**
404     * Creates and subscribes a Subscriber that applies the given
405 dl 1.10 * stream operation to items, and uses the given bufferSize for
406 dl 1.1 * buffering. Returns a CompletableFuture that is completed
407     * normally with the result of this function when the publisher
408 dl 1.14 * signals {@code onComplete}, or is completed exceptionally upon
409     * any error.
410 dl 1.1 *
411     * <p><b>Preliminary release note:</b> Currently, this method
412     * collects all items before executing the stream
413     * computation. Improvements are pending Stream integration.
414     *
415 jsr166 1.4 * @param <T> the published item type
416     * @param <R> the result type of the stream function
417 dl 1.10 * @param bufferSize the request size for subscriptions
418 dl 1.1 * @param publisher the publisher
419     * @param streamFunction the operation on elements
420     * @return a CompletableFuture that is completed normally with the
421     * result of the given function as result when the publisher signals
422 jsr166 1.7 * onComplete, and exceptionally upon any error
423 dl 1.1 * @throws NullPointerException if publisher or function are null
424 dl 1.10 * @throws IllegalArgumentException if bufferSize not positive
425 dl 1.1 */
426     public static <T,R> CompletableFuture<R> stream(
427 dl 1.10 long bufferSize, Publisher<T> publisher,
428 dl 1.1 Function<? super Stream<T>, ? extends R> streamFunction) {
429 dl 1.10 if (bufferSize <= 0L)
430     throw new IllegalArgumentException("bufferSize must be positive");
431 dl 1.1 if (publisher == null || streamFunction == null)
432     throw new NullPointerException();
433     CompletableFuture<R> status = new CompletableFuture<>();
434     publisher.subscribe(new StreamSubscriber<T,R>(
435 dl 1.10 bufferSize, status, streamFunction));
436 dl 1.1 return status;
437     }
438 jsr166 1.2
439 dl 1.1 /**
440     * Equivalent to {@link #stream(long, Publisher, Function)}
441 dl 1.18 * with {@link #defaultBufferSize}.
442 dl 1.1 *
443 jsr166 1.4 * @param <T> the published item type
444     * @param <R> the result type of the stream function
445 dl 1.1 * @param publisher the publisher
446     * @param streamFunction the operation on elements
447     * @return a CompletableFuture that is completed normally with the
448     * result of the given function as result when the publisher signals
449 jsr166 1.7 * onComplete, and exceptionally upon any error
450 dl 1.1 * @throws NullPointerException if publisher or function are null
451     */
452     public static <T,R> CompletableFuture<R> stream(
453 jsr166 1.2 Publisher<T> publisher,
454 dl 1.1 Function<? super Stream<T>,? extends R> streamFunction) {
455 dl 1.18 return stream(defaultBufferSize(), publisher, streamFunction);
456 dl 1.1 }
457     }