ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Flow.java
Revision: 1.16
Committed: Mon Jan 19 18:06:23 2015 UTC (9 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.15: +19 -14 lines
Log Message:
Improve example

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