ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Flow.java
Revision: 1.18
Committed: Fri Jan 23 13:48:41 2015 UTC (9 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.17: +24 -7 lines
Log Message:
Expand spin/help/block cases; add defaults

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.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     * signal with an {@link IllegalArgumentException}
251     * argument. Otherwise, the Subscriber will receive up to
252     * {@code n} additional {@code onNext} invocations (or fewer
253     * if 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.3 abstract static class CompletableSubscriber<T,U> implements Subscriber<T>,
297 dl 1.1 Consumer<T> {
298     final CompletableFuture<U> status;
299     Subscription subscription;
300 dl 1.10 long requestSize;
301 jsr166 1.2 long count;
302 dl 1.10 CompletableSubscriber(long bufferSize, CompletableFuture<U> status) {
303 dl 1.1 this.status = status;
304 dl 1.10 this.requestSize = bufferSize;
305 dl 1.1 }
306     public final void onSubscribe(Subscription subscription) {
307     (this.subscription = subscription).request(requestSize);
308 dl 1.10 count = requestSize -= (requestSize >>> 1);
309 dl 1.1 }
310 jsr166 1.2 public final void onError(Throwable ex) {
311 dl 1.1 status.completeExceptionally(ex);
312     }
313     public void onNext(T item) {
314 dl 1.10 try {
315     if (--count <= 0)
316     subscription.request(count = requestSize);
317     accept(item);
318     } catch (Throwable ex) {
319     status.completeExceptionally(ex);
320 dl 1.1 }
321     }
322     }
323 jsr166 1.2
324 dl 1.1 static final class ConsumeSubscriber<T> extends CompletableSubscriber<T,Void> {
325     final Consumer<? super T> consumer;
326 dl 1.10 ConsumeSubscriber(long bufferSize,
327 dl 1.1 CompletableFuture<Void> status,
328     Consumer<? super T> consumer) {
329 dl 1.10 super(bufferSize, status);
330 dl 1.1 this.consumer = consumer;
331     }
332     public void accept(T item) { consumer.accept(item); }
333     public void onComplete() { status.complete(null); }
334     }
335    
336     /**
337     * Creates and subscribes a Subscriber that consumes all items
338     * from the given publisher using the given Consumer function, and
339 dl 1.10 * using the given bufferSize for buffering. Returns a
340 dl 1.1 * CompletableFuture that is completed normally when the publisher
341 dl 1.14 * signals {@code onComplete}, or completed exceptionally upon any
342     * error, including an exception thrown by the Consumer (in which
343     * case the subscription is cancelled if not already terminated).
344 dl 1.1 *
345 jsr166 1.4 * @param <T> the published item type
346 dl 1.10 * @param bufferSize the request size for subscriptions
347 dl 1.1 * @param publisher the publisher
348     * @param consumer the function applied to each onNext item
349     * @return a CompletableFuture that is completed normally
350     * when the publisher signals onComplete, and exceptionally
351 jsr166 1.7 * upon any error
352 dl 1.1 * @throws NullPointerException if publisher or consumer are null
353 dl 1.10 * @throws IllegalArgumentException if bufferSize not positive
354 dl 1.1 */
355     public static <T> CompletableFuture<Void> consume(
356 dl 1.10 long bufferSize, Publisher<T> publisher, Consumer<? super T> consumer) {
357     if (bufferSize <= 0L)
358     throw new IllegalArgumentException("bufferSize must be positive");
359 dl 1.1 if (publisher == null || consumer == null)
360     throw new NullPointerException();
361     CompletableFuture<Void> status = new CompletableFuture<>();
362     publisher.subscribe(new ConsumeSubscriber<T>(
363 dl 1.10 bufferSize, status, consumer));
364 dl 1.1 return status;
365     }
366    
367     /**
368     * Equivalent to {@link #consume(long, Publisher, Consumer)}
369 dl 1.18 * with {@link #defaultBufferSize}.
370 dl 1.1 *
371 jsr166 1.4 * @param <T> the published item type
372 dl 1.1 * @param publisher the publisher
373     * @param consumer the function applied to each onNext item
374     * @return a CompletableFuture that is completed normally
375     * when the publisher signals onComplete, and exceptionally
376 jsr166 1.7 * upon any error
377 dl 1.1 * @throws NullPointerException if publisher or consumer are null
378     */
379     public static <T> CompletableFuture<Void> consume(
380     Publisher<T> publisher, Consumer<? super T> consumer) {
381 dl 1.18 return consume(defaultBufferSize(), publisher, consumer);
382 dl 1.1 }
383    
384     /**
385     * Temporary implementation for Stream, collecting all items
386     * and then applying stream operation.
387     */
388     static final class StreamSubscriber<T,R> extends CompletableSubscriber<T,R> {
389     final Function<? super Stream<T>, ? extends R> fn;
390     final ArrayList<T> items;
391 dl 1.10 StreamSubscriber(long bufferSize,
392 dl 1.1 CompletableFuture<R> status,
393     Function<? super Stream<T>, ? extends R> fn) {
394 dl 1.10 super(bufferSize, status);
395 dl 1.1 this.fn = fn;
396     this.items = new ArrayList<T>();
397     }
398     public void accept(T item) { items.add(item); }
399     public void onComplete() { status.complete(fn.apply(items.stream())); }
400     }
401    
402     /**
403     * Creates and subscribes a Subscriber that applies the given
404 dl 1.10 * stream operation to items, and uses the given bufferSize for
405 dl 1.1 * buffering. Returns a CompletableFuture that is completed
406     * normally with the result of this function when the publisher
407 dl 1.14 * signals {@code onComplete}, or is completed exceptionally upon
408     * any error.
409 dl 1.1 *
410     * <p><b>Preliminary release note:</b> Currently, this method
411     * collects all items before executing the stream
412     * computation. Improvements are pending Stream integration.
413     *
414 jsr166 1.4 * @param <T> the published item type
415     * @param <R> the result type of the stream function
416 dl 1.10 * @param bufferSize the request size for subscriptions
417 dl 1.1 * @param publisher the publisher
418     * @param streamFunction the operation on elements
419     * @return a CompletableFuture that is completed normally with the
420     * result of the given function as result when the publisher signals
421 jsr166 1.7 * onComplete, and exceptionally upon any error
422 dl 1.1 * @throws NullPointerException if publisher or function are null
423 dl 1.10 * @throws IllegalArgumentException if bufferSize not positive
424 dl 1.1 */
425     public static <T,R> CompletableFuture<R> stream(
426 dl 1.10 long bufferSize, Publisher<T> publisher,
427 dl 1.1 Function<? super Stream<T>, ? extends R> streamFunction) {
428 dl 1.10 if (bufferSize <= 0L)
429     throw new IllegalArgumentException("bufferSize must be positive");
430 dl 1.1 if (publisher == null || streamFunction == null)
431     throw new NullPointerException();
432     CompletableFuture<R> status = new CompletableFuture<>();
433     publisher.subscribe(new StreamSubscriber<T,R>(
434 dl 1.10 bufferSize, status, streamFunction));
435 dl 1.1 return status;
436     }
437 jsr166 1.2
438 dl 1.1 /**
439     * Equivalent to {@link #stream(long, Publisher, Function)}
440 dl 1.18 * with {@link #defaultBufferSize}.
441 dl 1.1 *
442 jsr166 1.4 * @param <T> the published item type
443     * @param <R> the result type of the stream function
444 dl 1.1 * @param publisher the publisher
445     * @param streamFunction the operation on elements
446     * @return a CompletableFuture that is completed normally with the
447     * result of the given function as result when the publisher signals
448 jsr166 1.7 * onComplete, and exceptionally upon any error
449 dl 1.1 * @throws NullPointerException if publisher or function are null
450     */
451     public static <T,R> CompletableFuture<R> stream(
452 jsr166 1.2 Publisher<T> publisher,
453 dl 1.1 Function<? super Stream<T>,? extends R> streamFunction) {
454 dl 1.18 return stream(defaultBufferSize(), publisher, streamFunction);
455 dl 1.1 }
456     }