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

# Content
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
9 import java.util.ArrayList;
10 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}.
20 *
21 * <p>These interfaces correspond to the <a
22 * href="http://www.reactive-streams.org/"> reactive-streams</a>
23 * specification. They apply in both concurrent and distributed
24 * asynchronous settings: All (seven) methods are defined in {@code
25 * void} "one-way" 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 *
30 * <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 * 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 *
41 * <pre> {@code
42 * class OneShotPublisher implements Publisher<Boolean> {
43 * final ExecutorService executor = ForkJoinPool.commonPool(); // daemon-based
44 * 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 * subscriber.onSubscribe(new OneShotSubscription(subscriber, executor));
51 * }
52 * }
53 * static class OneShotSubscription implements Subscription {
54 * final Subscriber<? super Boolean> subscriber;
55 * final ExecutorService executor;
56 * Future<?> future; // to allow cancellation
57 * boolean completed = false;
58 * OneShotSubscription(Subscriber<? super Boolean> subscriber,
59 * ExecutorService executor) {
60 * this.subscriber = subscriber;
61 * this.executor = executor;
62 * }
63 * public synchronized void request(long n) {
64 * if (n != 0 && !completed) {
65 * completed = true;
66 * future = executor.submit(() -> {
67 * if (n < 0)
68 * subscriber.onError(new IllegalArgumentException());
69 * else {
70 * subscriber.onNext(Boolean.TRUE);
71 * subscriber.onComplete();
72 * }});
73 * }
74 * }
75 * public synchronized void cancel() {
76 * completed = true;
77 * if (future != null) future.cancel(false);
78 * }
79 * }
80 * }}</pre>
81 *
82 * <p>A {@link Subscriber} arranges that items be requested and
83 * 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 * 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 *
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 *
120 * <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 *
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 *
138 * @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 * items (via method {@code onNext}) in the same order, unless
149 * drops or errors are encountered. If a Publisher encounters an
150 * 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 * invocations for each subscription are strictly ordered in <a
156 * href="package-summary.html#MemoryVisibility"><i>happens-before</i></a>
157 * order.
158 *
159 * <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 *
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 * 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 *
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 * A receiver of messages. The methods in this interface are
188 * invoked in strict sequential order for each {@link
189 * Subscription}.
190 *
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 * <p>Typically, implementations of this method invoke {@code
201 * subscription.request} to enable receiving items.
202 *
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 * 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 * undefined.
234 */
235 public void onComplete();
236 }
237
238 /**
239 * 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 */
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 * negative, the Subscriber will receive an {@code onError}
250 * 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 *
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 * Causes the Subscriber to (eventually) stop receiving
262 * 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 */
267 public void cancel();
268 }
269
270 /**
271 * A component that acts as both a Subscriber and Publisher.
272 *
273 * @param <T> the subscribed item type
274 * @param <R> the published item type
275 */
276 public static interface Processor<T,R> extends Subscriber<T>, Publisher<R> {
277 }
278
279 // Support for static methods
280
281 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
296 abstract static class CompletableSubscriber<T,U>
297 implements Subscriber<T>, Consumer<T>
298 {
299 final CompletableFuture<U> status;
300 Subscription subscription;
301 long requestSize;
302 long count;
303 CompletableSubscriber(long bufferSize, CompletableFuture<U> status) {
304 this.status = status;
305 this.requestSize = bufferSize;
306 }
307 public final void onSubscribe(Subscription subscription) {
308 (this.subscription = subscription).request(requestSize);
309 count = requestSize -= (requestSize >>> 1);
310 }
311 public final void onError(Throwable ex) {
312 status.completeExceptionally(ex);
313 }
314 public void onNext(T item) {
315 try {
316 if (--count <= 0)
317 subscription.request(count = requestSize);
318 accept(item);
319 } catch (Throwable ex) {
320 status.completeExceptionally(ex);
321 }
322 }
323 }
324
325 static final class ConsumeSubscriber<T> extends CompletableSubscriber<T,Void> {
326 final Consumer<? super T> consumer;
327 ConsumeSubscriber(long bufferSize,
328 CompletableFuture<Void> status,
329 Consumer<? super T> consumer) {
330 super(bufferSize, status);
331 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 * using the given bufferSize for buffering. Returns a
341 * CompletableFuture that is completed normally when the publisher
342 * 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 *
346 * @param <T> the published item type
347 * @param bufferSize the request size for subscriptions
348 * @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 * upon any error
353 * @throws NullPointerException if publisher or consumer are null
354 * @throws IllegalArgumentException if bufferSize not positive
355 */
356 public static <T> CompletableFuture<Void> consume(
357 long bufferSize, Publisher<T> publisher, Consumer<? super T> consumer) {
358 if (bufferSize <= 0L)
359 throw new IllegalArgumentException("bufferSize must be positive");
360 if (publisher == null || consumer == null)
361 throw new NullPointerException();
362 CompletableFuture<Void> status = new CompletableFuture<>();
363 publisher.subscribe(new ConsumeSubscriber<T>(
364 bufferSize, status, consumer));
365 return status;
366 }
367
368 /**
369 * Equivalent to {@link #consume(long, Publisher, Consumer)}
370 * with {@link #defaultBufferSize}.
371 *
372 * @param <T> the published item type
373 * @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 * upon any error
378 * @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 return consume(defaultBufferSize(), publisher, consumer);
383 }
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 StreamSubscriber(long bufferSize,
393 CompletableFuture<R> status,
394 Function<? super Stream<T>, ? extends R> fn) {
395 super(bufferSize, status);
396 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 * stream operation to items, and uses the given bufferSize for
406 * buffering. Returns a CompletableFuture that is completed
407 * normally with the result of this function when the publisher
408 * signals {@code onComplete}, or is completed exceptionally upon
409 * any error.
410 *
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 * @param <T> the published item type
416 * @param <R> the result type of the stream function
417 * @param bufferSize the request size for subscriptions
418 * @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 * onComplete, and exceptionally upon any error
423 * @throws NullPointerException if publisher or function are null
424 * @throws IllegalArgumentException if bufferSize not positive
425 */
426 public static <T,R> CompletableFuture<R> stream(
427 long bufferSize, Publisher<T> publisher,
428 Function<? super Stream<T>, ? extends R> streamFunction) {
429 if (bufferSize <= 0L)
430 throw new IllegalArgumentException("bufferSize must be positive");
431 if (publisher == null || streamFunction == null)
432 throw new NullPointerException();
433 CompletableFuture<R> status = new CompletableFuture<>();
434 publisher.subscribe(new StreamSubscriber<T,R>(
435 bufferSize, status, streamFunction));
436 return status;
437 }
438
439 /**
440 * Equivalent to {@link #stream(long, Publisher, Function)}
441 * with {@link #defaultBufferSize}.
442 *
443 * @param <T> the published item type
444 * @param <R> the result type of the stream function
445 * @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 * onComplete, and exceptionally upon any error
450 * @throws NullPointerException if publisher or function are null
451 */
452 public static <T,R> CompletableFuture<R> stream(
453 Publisher<T> publisher,
454 Function<? super Stream<T>,? extends R> streamFunction) {
455 return stream(defaultBufferSize(), publisher, streamFunction);
456 }
457 }