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