ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Flow.java
Revision: 1.13
Committed: Mon Jan 19 00:49:29 2015 UTC (9 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.12: +2 -2 lines
Log Message:
whitespace

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