author | dl |
Fri, 15 Jul 2016 13:55:51 -0700 | |
changeset 39723 | 9aa34e4a0469 |
parent 36936 | bfcdf736a998 |
child 40734 | 48879ea67e2a |
permissions | -rw-r--r-- |
32989 | 1 |
/* |
2 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
|
3 |
* |
|
4 |
* This code is free software; you can redistribute it and/or modify it |
|
5 |
* under the terms of the GNU General Public License version 2 only, as |
|
6 |
* published by the Free Software Foundation. Oracle designates this |
|
7 |
* particular file as subject to the "Classpath" exception as provided |
|
8 |
* by Oracle in the LICENSE file that accompanied this code. |
|
9 |
* |
|
10 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
11 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
12 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
13 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
14 |
* accompanied this code). |
|
15 |
* |
|
16 |
* You should have received a copy of the GNU General Public License version |
|
17 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
18 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
19 |
* |
|
20 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
|
21 |
* or visit www.oracle.com if you need additional information or have any |
|
22 |
* questions. |
|
23 |
*/ |
|
24 |
||
25 |
/* |
|
26 |
* This file is available under and governed by the GNU General Public |
|
27 |
* License version 2 only, as published by the Free Software Foundation. |
|
28 |
* However, the following notice accompanied the original version of this |
|
29 |
* file: |
|
30 |
* |
|
31 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
|
32 |
* Expert Group and released to the public domain, as explained at |
|
33 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
|
34 |
*/ |
|
35 |
||
36 |
package java.util.concurrent; |
|
37 |
||
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
38 |
import java.lang.invoke.MethodHandles; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
39 |
import java.lang.invoke.VarHandle; |
32989 | 40 |
import java.util.ArrayList; |
41 |
import java.util.List; |
|
42 |
import java.util.concurrent.locks.LockSupport; |
|
43 |
import java.util.function.BiConsumer; |
|
44 |
import java.util.function.BiPredicate; |
|
45 |
import java.util.function.Consumer; |
|
46 |
||
47 |
/** |
|
48 |
* A {@link Flow.Publisher} that asynchronously issues submitted |
|
49 |
* (non-null) items to current subscribers until it is closed. Each |
|
50 |
* current subscriber receives newly submitted items in the same order |
|
51 |
* unless drops or exceptions are encountered. Using a |
|
52 |
* SubmissionPublisher allows item generators to act as compliant <a |
|
53 |
* href="http://www.reactive-streams.org/"> reactive-streams</a> |
|
54 |
* Publishers relying on drop handling and/or blocking for flow |
|
55 |
* control. |
|
56 |
* |
|
57 |
* <p>A SubmissionPublisher uses the {@link Executor} supplied in its |
|
58 |
* constructor for delivery to subscribers. The best choice of |
|
59 |
* Executor depends on expected usage. If the generator(s) of |
|
60 |
* submitted items run in separate threads, and the number of |
|
61 |
* subscribers can be estimated, consider using a {@link |
|
62 |
* Executors#newFixedThreadPool}. Otherwise consider using the |
|
63 |
* default, normally the {@link ForkJoinPool#commonPool}. |
|
64 |
* |
|
65 |
* <p>Buffering allows producers and consumers to transiently operate |
|
66 |
* at different rates. Each subscriber uses an independent buffer. |
|
67 |
* Buffers are created upon first use and expanded as needed up to the |
|
68 |
* given maximum. (The enforced capacity may be rounded up to the |
|
69 |
* nearest power of two and/or bounded by the largest value supported |
|
70 |
* by this implementation.) Invocations of {@link |
|
71 |
* Flow.Subscription#request(long) request} do not directly result in |
|
72 |
* buffer expansion, but risk saturation if unfilled requests exceed |
|
73 |
* the maximum capacity. The default value of {@link |
|
74 |
* Flow#defaultBufferSize()} may provide a useful starting point for |
|
75 |
* choosing a capacity based on expected rates, resources, and usages. |
|
76 |
* |
|
77 |
* <p>Publication methods support different policies about what to do |
|
78 |
* when buffers are saturated. Method {@link #submit(Object) submit} |
|
79 |
* blocks until resources are available. This is simplest, but least |
|
80 |
* responsive. The {@code offer} methods may drop items (either |
|
81 |
* immediately or with bounded timeout), but provide an opportunity to |
|
82 |
* interpose a handler and then retry. |
|
83 |
* |
|
84 |
* <p>If any Subscriber method throws an exception, its subscription |
|
85 |
* is cancelled. If a handler is supplied as a constructor argument, |
|
86 |
* it is invoked before cancellation upon an exception in method |
|
87 |
* {@link Flow.Subscriber#onNext onNext}, but exceptions in methods |
|
88 |
* {@link Flow.Subscriber#onSubscribe onSubscribe}, |
|
89 |
* {@link Flow.Subscriber#onError(Throwable) onError} and |
|
90 |
* {@link Flow.Subscriber#onComplete() onComplete} are not recorded or |
|
91 |
* handled before cancellation. If the supplied Executor throws |
|
92 |
* {@link RejectedExecutionException} (or any other RuntimeException |
|
93 |
* or Error) when attempting to execute a task, or a drop handler |
|
94 |
* throws an exception when processing a dropped item, then the |
|
95 |
* exception is rethrown. In these cases, not all subscribers will |
|
96 |
* have been issued the published item. It is usually good practice to |
|
97 |
* {@link #closeExceptionally closeExceptionally} in these cases. |
|
98 |
* |
|
99 |
* <p>Method {@link #consume(Consumer)} simplifies support for a |
|
100 |
* common case in which the only action of a subscriber is to request |
|
101 |
* and process all items using a supplied function. |
|
102 |
* |
|
103 |
* <p>This class may also serve as a convenient base for subclasses |
|
104 |
* that generate items, and use the methods in this class to publish |
|
105 |
* them. For example here is a class that periodically publishes the |
|
106 |
* items generated from a supplier. (In practice you might add methods |
|
107 |
* to independently start and stop generation, to share Executors |
|
108 |
* among publishers, and so on, or use a SubmissionPublisher as a |
|
109 |
* component rather than a superclass.) |
|
110 |
* |
|
111 |
* <pre> {@code |
|
112 |
* class PeriodicPublisher<T> extends SubmissionPublisher<T> { |
|
113 |
* final ScheduledFuture<?> periodicTask; |
|
114 |
* final ScheduledExecutorService scheduler; |
|
115 |
* PeriodicPublisher(Executor executor, int maxBufferCapacity, |
|
116 |
* Supplier<? extends T> supplier, |
|
117 |
* long period, TimeUnit unit) { |
|
118 |
* super(executor, maxBufferCapacity); |
|
119 |
* scheduler = new ScheduledThreadPoolExecutor(1); |
|
120 |
* periodicTask = scheduler.scheduleAtFixedRate( |
|
121 |
* () -> submit(supplier.get()), 0, period, unit); |
|
122 |
* } |
|
123 |
* public void close() { |
|
124 |
* periodicTask.cancel(false); |
|
125 |
* scheduler.shutdown(); |
|
126 |
* super.close(); |
|
127 |
* } |
|
128 |
* }}</pre> |
|
129 |
* |
|
130 |
* <p>Here is an example of a {@link Flow.Processor} implementation. |
|
131 |
* It uses single-step requests to its publisher for simplicity of |
|
132 |
* illustration. A more adaptive version could monitor flow using the |
|
133 |
* lag estimate returned from {@code submit}, along with other utility |
|
134 |
* methods. |
|
135 |
* |
|
136 |
* <pre> {@code |
|
137 |
* class TransformProcessor<S,T> extends SubmissionPublisher<T> |
|
138 |
* implements Flow.Processor<S,T> { |
|
139 |
* final Function<? super S, ? extends T> function; |
|
140 |
* Flow.Subscription subscription; |
|
141 |
* TransformProcessor(Executor executor, int maxBufferCapacity, |
|
142 |
* Function<? super S, ? extends T> function) { |
|
143 |
* super(executor, maxBufferCapacity); |
|
144 |
* this.function = function; |
|
145 |
* } |
|
146 |
* public void onSubscribe(Flow.Subscription subscription) { |
|
147 |
* (this.subscription = subscription).request(1); |
|
148 |
* } |
|
149 |
* public void onNext(S item) { |
|
150 |
* subscription.request(1); |
|
151 |
* submit(function.apply(item)); |
|
152 |
* } |
|
153 |
* public void onError(Throwable ex) { closeExceptionally(ex); } |
|
154 |
* public void onComplete() { close(); } |
|
155 |
* }}</pre> |
|
156 |
* |
|
157 |
* @param <T> the published item type |
|
158 |
* @author Doug Lea |
|
35302
e4d2275861c3
8136494: Update "@since 1.9" to "@since 9" to match java.version.specification
iris
parents:
34369
diff
changeset
|
159 |
* @since 9 |
32989 | 160 |
*/ |
161 |
public class SubmissionPublisher<T> implements Flow.Publisher<T>, |
|
162 |
AutoCloseable { |
|
163 |
/* |
|
164 |
* Most mechanics are handled by BufferedSubscription. This class |
|
165 |
* mainly tracks subscribers and ensures sequentiality, by using |
|
166 |
* built-in synchronization locks across public methods. (Using |
|
167 |
* built-in locks works well in the most typical case in which |
|
168 |
* only one thread submits items). |
|
169 |
*/ |
|
170 |
||
171 |
/** The largest possible power of two array size. */ |
|
172 |
static final int BUFFER_CAPACITY_LIMIT = 1 << 30; |
|
173 |
||
174 |
/** Round capacity to power of 2, at most limit. */ |
|
175 |
static final int roundCapacity(int cap) { |
|
176 |
int n = cap - 1; |
|
177 |
n |= n >>> 1; |
|
178 |
n |= n >>> 2; |
|
179 |
n |= n >>> 4; |
|
180 |
n |= n >>> 8; |
|
181 |
n |= n >>> 16; |
|
182 |
return (n <= 0) ? 1 : // at least 1 |
|
183 |
(n >= BUFFER_CAPACITY_LIMIT) ? BUFFER_CAPACITY_LIMIT : n + 1; |
|
184 |
} |
|
185 |
||
186 |
// default Executor setup; nearly the same as CompletableFuture |
|
187 |
||
188 |
/** |
|
189 |
* Default executor -- ForkJoinPool.commonPool() unless it cannot |
|
190 |
* support parallelism. |
|
191 |
*/ |
|
192 |
private static final Executor ASYNC_POOL = |
|
193 |
(ForkJoinPool.getCommonPoolParallelism() > 1) ? |
|
194 |
ForkJoinPool.commonPool() : new ThreadPerTaskExecutor(); |
|
195 |
||
196 |
/** Fallback if ForkJoinPool.commonPool() cannot support parallelism */ |
|
197 |
private static final class ThreadPerTaskExecutor implements Executor { |
|
198 |
public void execute(Runnable r) { new Thread(r).start(); } |
|
199 |
} |
|
200 |
||
201 |
/** |
|
202 |
* Clients (BufferedSubscriptions) are maintained in a linked list |
|
203 |
* (via their "next" fields). This works well for publish loops. |
|
204 |
* It requires O(n) traversal to check for duplicate subscribers, |
|
205 |
* but we expect that subscribing is much less common than |
|
206 |
* publishing. Unsubscribing occurs only during traversal loops, |
|
207 |
* when BufferedSubscription methods return negative values |
|
208 |
* signifying that they have been disabled. To reduce |
|
209 |
* head-of-line blocking, submit and offer methods first call |
|
210 |
* BufferedSubscription.offer on each subscriber, and place |
|
211 |
* saturated ones in retries list (using nextRetry field), and |
|
212 |
* retry, possibly blocking or dropping. |
|
213 |
*/ |
|
214 |
BufferedSubscription<T> clients; |
|
215 |
||
216 |
/** Run status, updated only within locks */ |
|
217 |
volatile boolean closed; |
|
218 |
/** If non-null, the exception in closeExceptionally */ |
|
219 |
volatile Throwable closedException; |
|
220 |
||
221 |
// Parameters for constructing BufferedSubscriptions |
|
222 |
final Executor executor; |
|
223 |
final BiConsumer<? super Flow.Subscriber<? super T>, ? super Throwable> onNextHandler; |
|
224 |
final int maxBufferCapacity; |
|
225 |
||
226 |
/** |
|
227 |
* Creates a new SubmissionPublisher using the given Executor for |
|
228 |
* async delivery to subscribers, with the given maximum buffer size |
|
229 |
* for each subscriber, and, if non-null, the given handler invoked |
|
230 |
* when any Subscriber throws an exception in method {@link |
|
231 |
* Flow.Subscriber#onNext(Object) onNext}. |
|
232 |
* |
|
233 |
* @param executor the executor to use for async delivery, |
|
234 |
* supporting creation of at least one independent thread |
|
235 |
* @param maxBufferCapacity the maximum capacity for each |
|
236 |
* subscriber's buffer (the enforced capacity may be rounded up to |
|
237 |
* the nearest power of two and/or bounded by the largest value |
|
238 |
* supported by this implementation; method {@link #getMaxBufferCapacity} |
|
239 |
* returns the actual value) |
|
240 |
* @param handler if non-null, procedure to invoke upon exception |
|
241 |
* thrown in method {@code onNext} |
|
242 |
* @throws NullPointerException if executor is null |
|
243 |
* @throws IllegalArgumentException if maxBufferCapacity not |
|
244 |
* positive |
|
245 |
*/ |
|
246 |
public SubmissionPublisher(Executor executor, int maxBufferCapacity, |
|
247 |
BiConsumer<? super Flow.Subscriber<? super T>, ? super Throwable> handler) { |
|
248 |
if (executor == null) |
|
249 |
throw new NullPointerException(); |
|
250 |
if (maxBufferCapacity <= 0) |
|
251 |
throw new IllegalArgumentException("capacity must be positive"); |
|
252 |
this.executor = executor; |
|
253 |
this.onNextHandler = handler; |
|
254 |
this.maxBufferCapacity = roundCapacity(maxBufferCapacity); |
|
255 |
} |
|
256 |
||
257 |
/** |
|
258 |
* Creates a new SubmissionPublisher using the given Executor for |
|
259 |
* async delivery to subscribers, with the given maximum buffer size |
|
260 |
* for each subscriber, and no handler for Subscriber exceptions in |
|
261 |
* method {@link Flow.Subscriber#onNext(Object) onNext}. |
|
262 |
* |
|
263 |
* @param executor the executor to use for async delivery, |
|
264 |
* supporting creation of at least one independent thread |
|
265 |
* @param maxBufferCapacity the maximum capacity for each |
|
266 |
* subscriber's buffer (the enforced capacity may be rounded up to |
|
267 |
* the nearest power of two and/or bounded by the largest value |
|
268 |
* supported by this implementation; method {@link #getMaxBufferCapacity} |
|
269 |
* returns the actual value) |
|
270 |
* @throws NullPointerException if executor is null |
|
271 |
* @throws IllegalArgumentException if maxBufferCapacity not |
|
272 |
* positive |
|
273 |
*/ |
|
274 |
public SubmissionPublisher(Executor executor, int maxBufferCapacity) { |
|
275 |
this(executor, maxBufferCapacity, null); |
|
276 |
} |
|
277 |
||
278 |
/** |
|
279 |
* Creates a new SubmissionPublisher using the {@link |
|
280 |
* ForkJoinPool#commonPool()} for async delivery to subscribers |
|
281 |
* (unless it does not support a parallelism level of at least two, |
|
282 |
* in which case, a new Thread is created to run each task), with |
|
283 |
* maximum buffer capacity of {@link Flow#defaultBufferSize}, and no |
|
284 |
* handler for Subscriber exceptions in method {@link |
|
285 |
* Flow.Subscriber#onNext(Object) onNext}. |
|
286 |
*/ |
|
287 |
public SubmissionPublisher() { |
|
288 |
this(ASYNC_POOL, Flow.defaultBufferSize(), null); |
|
289 |
} |
|
290 |
||
291 |
/** |
|
292 |
* Adds the given Subscriber unless already subscribed. If already |
|
293 |
* subscribed, the Subscriber's {@link |
|
294 |
* Flow.Subscriber#onError(Throwable) onError} method is invoked on |
|
295 |
* the existing subscription with an {@link IllegalStateException}. |
|
296 |
* Otherwise, upon success, the Subscriber's {@link |
|
297 |
* Flow.Subscriber#onSubscribe onSubscribe} method is invoked |
|
298 |
* asynchronously with a new {@link Flow.Subscription}. If {@link |
|
299 |
* Flow.Subscriber#onSubscribe onSubscribe} throws an exception, the |
|
300 |
* subscription is cancelled. Otherwise, if this SubmissionPublisher |
|
301 |
* was closed exceptionally, then the subscriber's {@link |
|
302 |
* Flow.Subscriber#onError onError} method is invoked with the |
|
303 |
* corresponding exception, or if closed without exception, the |
|
304 |
* subscriber's {@link Flow.Subscriber#onComplete() onComplete} |
|
305 |
* method is invoked. Subscribers may enable receiving items by |
|
306 |
* invoking the {@link Flow.Subscription#request(long) request} |
|
307 |
* method of the new Subscription, and may unsubscribe by invoking |
|
308 |
* its {@link Flow.Subscription#cancel() cancel} method. |
|
309 |
* |
|
310 |
* @param subscriber the subscriber |
|
311 |
* @throws NullPointerException if subscriber is null |
|
312 |
*/ |
|
313 |
public void subscribe(Flow.Subscriber<? super T> subscriber) { |
|
314 |
if (subscriber == null) throw new NullPointerException(); |
|
315 |
BufferedSubscription<T> subscription = |
|
316 |
new BufferedSubscription<T>(subscriber, executor, |
|
317 |
onNextHandler, maxBufferCapacity); |
|
318 |
synchronized (this) { |
|
319 |
for (BufferedSubscription<T> b = clients, pred = null;;) { |
|
320 |
if (b == null) { |
|
321 |
Throwable ex; |
|
322 |
subscription.onSubscribe(); |
|
323 |
if ((ex = closedException) != null) |
|
324 |
subscription.onError(ex); |
|
325 |
else if (closed) |
|
326 |
subscription.onComplete(); |
|
327 |
else if (pred == null) |
|
328 |
clients = subscription; |
|
329 |
else |
|
330 |
pred.next = subscription; |
|
331 |
break; |
|
332 |
} |
|
333 |
BufferedSubscription<T> next = b.next; |
|
334 |
if (b.isDisabled()) { // remove |
|
335 |
b.next = null; // detach |
|
336 |
if (pred == null) |
|
337 |
clients = next; |
|
338 |
else |
|
339 |
pred.next = next; |
|
340 |
} |
|
341 |
else if (subscriber.equals(b.subscriber)) { |
|
342 |
b.onError(new IllegalStateException("Duplicate subscribe")); |
|
343 |
break; |
|
344 |
} |
|
345 |
else |
|
346 |
pred = b; |
|
347 |
b = next; |
|
348 |
} |
|
349 |
} |
|
350 |
} |
|
351 |
||
352 |
/** |
|
353 |
* Publishes the given item to each current subscriber by |
|
354 |
* asynchronously invoking its {@link Flow.Subscriber#onNext(Object) |
|
355 |
* onNext} method, blocking uninterruptibly while resources for any |
|
356 |
* subscriber are unavailable. This method returns an estimate of |
|
357 |
* the maximum lag (number of items submitted but not yet consumed) |
|
358 |
* among all current subscribers. This value is at least one |
|
359 |
* (accounting for this submitted item) if there are any |
|
360 |
* subscribers, else zero. |
|
361 |
* |
|
362 |
* <p>If the Executor for this publisher throws a |
|
363 |
* RejectedExecutionException (or any other RuntimeException or |
|
364 |
* Error) when attempting to asynchronously notify subscribers, |
|
365 |
* then this exception is rethrown, in which case not all |
|
366 |
* subscribers will have been issued this item. |
|
367 |
* |
|
368 |
* @param item the (non-null) item to publish |
|
369 |
* @return the estimated maximum lag among subscribers |
|
370 |
* @throws IllegalStateException if closed |
|
371 |
* @throws NullPointerException if item is null |
|
372 |
* @throws RejectedExecutionException if thrown by Executor |
|
373 |
*/ |
|
374 |
public int submit(T item) { |
|
375 |
if (item == null) throw new NullPointerException(); |
|
376 |
int lag = 0; |
|
377 |
boolean complete; |
|
378 |
synchronized (this) { |
|
379 |
complete = closed; |
|
380 |
BufferedSubscription<T> b = clients; |
|
381 |
if (!complete) { |
|
382 |
BufferedSubscription<T> pred = null, r = null, rtail = null; |
|
383 |
while (b != null) { |
|
384 |
BufferedSubscription<T> next = b.next; |
|
385 |
int stat = b.offer(item); |
|
386 |
if (stat < 0) { // disabled |
|
387 |
b.next = null; |
|
388 |
if (pred == null) |
|
389 |
clients = next; |
|
390 |
else |
|
391 |
pred.next = next; |
|
392 |
} |
|
393 |
else { |
|
394 |
if (stat > lag) |
|
395 |
lag = stat; |
|
396 |
else if (stat == 0) { // place on retry list |
|
397 |
b.nextRetry = null; |
|
398 |
if (rtail == null) |
|
399 |
r = b; |
|
400 |
else |
|
401 |
rtail.nextRetry = b; |
|
402 |
rtail = b; |
|
403 |
} |
|
404 |
pred = b; |
|
405 |
} |
|
406 |
b = next; |
|
407 |
} |
|
408 |
while (r != null) { |
|
409 |
BufferedSubscription<T> nextRetry = r.nextRetry; |
|
410 |
r.nextRetry = null; |
|
411 |
int stat = r.submit(item); |
|
412 |
if (stat > lag) |
|
413 |
lag = stat; |
|
414 |
else if (stat < 0 && clients == r) |
|
415 |
clients = r.next; // postpone internal unsubscribes |
|
416 |
r = nextRetry; |
|
417 |
} |
|
418 |
} |
|
419 |
} |
|
420 |
if (complete) |
|
421 |
throw new IllegalStateException("Closed"); |
|
422 |
else |
|
423 |
return lag; |
|
424 |
} |
|
425 |
||
426 |
/** |
|
427 |
* Publishes the given item, if possible, to each current subscriber |
|
428 |
* by asynchronously invoking its {@link |
|
429 |
* Flow.Subscriber#onNext(Object) onNext} method. The item may be |
|
430 |
* dropped by one or more subscribers if resource limits are |
|
431 |
* exceeded, in which case the given handler (if non-null) is |
|
432 |
* invoked, and if it returns true, retried once. Other calls to |
|
433 |
* methods in this class by other threads are blocked while the |
|
434 |
* handler is invoked. Unless recovery is assured, options are |
|
435 |
* usually limited to logging the error and/or issuing an {@link |
|
436 |
* Flow.Subscriber#onError(Throwable) onError} signal to the |
|
437 |
* subscriber. |
|
438 |
* |
|
439 |
* <p>This method returns a status indicator: If negative, it |
|
440 |
* represents the (negative) number of drops (failed attempts to |
|
441 |
* issue the item to a subscriber). Otherwise it is an estimate of |
|
442 |
* the maximum lag (number of items submitted but not yet |
|
443 |
* consumed) among all current subscribers. This value is at least |
|
444 |
* one (accounting for this submitted item) if there are any |
|
445 |
* subscribers, else zero. |
|
446 |
* |
|
447 |
* <p>If the Executor for this publisher throws a |
|
448 |
* RejectedExecutionException (or any other RuntimeException or |
|
449 |
* Error) when attempting to asynchronously notify subscribers, or |
|
450 |
* the drop handler throws an exception when processing a dropped |
|
451 |
* item, then this exception is rethrown. |
|
452 |
* |
|
453 |
* @param item the (non-null) item to publish |
|
454 |
* @param onDrop if non-null, the handler invoked upon a drop to a |
|
455 |
* subscriber, with arguments of the subscriber and item; if it |
|
456 |
* returns true, an offer is re-attempted (once) |
|
457 |
* @return if negative, the (negative) number of drops; otherwise |
|
458 |
* an estimate of maximum lag |
|
459 |
* @throws IllegalStateException if closed |
|
460 |
* @throws NullPointerException if item is null |
|
461 |
* @throws RejectedExecutionException if thrown by Executor |
|
462 |
*/ |
|
463 |
public int offer(T item, |
|
464 |
BiPredicate<Flow.Subscriber<? super T>, ? super T> onDrop) { |
|
465 |
return doOffer(0L, item, onDrop); |
|
466 |
} |
|
467 |
||
468 |
/** |
|
469 |
* Publishes the given item, if possible, to each current subscriber |
|
470 |
* by asynchronously invoking its {@link |
|
471 |
* Flow.Subscriber#onNext(Object) onNext} method, blocking while |
|
472 |
* resources for any subscription are unavailable, up to the |
|
473 |
* specified timeout or until the caller thread is interrupted, at |
|
474 |
* which point the given handler (if non-null) is invoked, and if it |
|
475 |
* returns true, retried once. (The drop handler may distinguish |
|
476 |
* timeouts from interrupts by checking whether the current thread |
|
477 |
* is interrupted.) Other calls to methods in this class by other |
|
478 |
* threads are blocked while the handler is invoked. Unless |
|
479 |
* recovery is assured, options are usually limited to logging the |
|
480 |
* error and/or issuing an {@link Flow.Subscriber#onError(Throwable) |
|
481 |
* onError} signal to the subscriber. |
|
482 |
* |
|
483 |
* <p>This method returns a status indicator: If negative, it |
|
484 |
* represents the (negative) number of drops (failed attempts to |
|
485 |
* issue the item to a subscriber). Otherwise it is an estimate of |
|
486 |
* the maximum lag (number of items submitted but not yet |
|
487 |
* consumed) among all current subscribers. This value is at least |
|
488 |
* one (accounting for this submitted item) if there are any |
|
489 |
* subscribers, else zero. |
|
490 |
* |
|
491 |
* <p>If the Executor for this publisher throws a |
|
492 |
* RejectedExecutionException (or any other RuntimeException or |
|
493 |
* Error) when attempting to asynchronously notify subscribers, or |
|
494 |
* the drop handler throws an exception when processing a dropped |
|
495 |
* item, then this exception is rethrown. |
|
496 |
* |
|
497 |
* @param item the (non-null) item to publish |
|
498 |
* @param timeout how long to wait for resources for any subscriber |
|
499 |
* before giving up, in units of {@code unit} |
|
500 |
* @param unit a {@code TimeUnit} determining how to interpret the |
|
501 |
* {@code timeout} parameter |
|
502 |
* @param onDrop if non-null, the handler invoked upon a drop to a |
|
503 |
* subscriber, with arguments of the subscriber and item; if it |
|
504 |
* returns true, an offer is re-attempted (once) |
|
505 |
* @return if negative, the (negative) number of drops; otherwise |
|
506 |
* an estimate of maximum lag |
|
507 |
* @throws IllegalStateException if closed |
|
508 |
* @throws NullPointerException if item is null |
|
509 |
* @throws RejectedExecutionException if thrown by Executor |
|
510 |
*/ |
|
511 |
public int offer(T item, long timeout, TimeUnit unit, |
|
512 |
BiPredicate<Flow.Subscriber<? super T>, ? super T> onDrop) { |
|
513 |
return doOffer(unit.toNanos(timeout), item, onDrop); |
|
514 |
} |
|
515 |
||
516 |
/** Common implementation for both forms of offer */ |
|
517 |
final int doOffer(long nanos, T item, |
|
518 |
BiPredicate<Flow.Subscriber<? super T>, ? super T> onDrop) { |
|
519 |
if (item == null) throw new NullPointerException(); |
|
520 |
int lag = 0, drops = 0; |
|
521 |
boolean complete; |
|
522 |
synchronized (this) { |
|
523 |
complete = closed; |
|
524 |
BufferedSubscription<T> b = clients; |
|
525 |
if (!complete) { |
|
526 |
BufferedSubscription<T> pred = null, r = null, rtail = null; |
|
527 |
while (b != null) { |
|
528 |
BufferedSubscription<T> next = b.next; |
|
529 |
int stat = b.offer(item); |
|
530 |
if (stat < 0) { |
|
531 |
b.next = null; |
|
532 |
if (pred == null) |
|
533 |
clients = next; |
|
534 |
else |
|
535 |
pred.next = next; |
|
536 |
} |
|
537 |
else { |
|
538 |
if (stat > lag) |
|
539 |
lag = stat; |
|
540 |
else if (stat == 0) { |
|
541 |
b.nextRetry = null; |
|
542 |
if (rtail == null) |
|
543 |
r = b; |
|
544 |
else |
|
545 |
rtail.nextRetry = b; |
|
546 |
rtail = b; |
|
547 |
} |
|
548 |
else if (stat > lag) |
|
549 |
lag = stat; |
|
550 |
pred = b; |
|
551 |
} |
|
552 |
b = next; |
|
553 |
} |
|
554 |
while (r != null) { |
|
555 |
BufferedSubscription<T> nextRetry = r.nextRetry; |
|
556 |
r.nextRetry = null; |
|
557 |
int stat = (nanos > 0L) ? r.timedOffer(item, nanos) : |
|
558 |
r.offer(item); |
|
559 |
if (stat == 0 && onDrop != null && |
|
560 |
onDrop.test(r.subscriber, item)) |
|
561 |
stat = r.offer(item); |
|
562 |
if (stat == 0) |
|
563 |
++drops; |
|
564 |
else if (stat > lag) |
|
565 |
lag = stat; |
|
566 |
else if (stat < 0 && clients == r) |
|
567 |
clients = r.next; |
|
568 |
r = nextRetry; |
|
569 |
} |
|
570 |
} |
|
571 |
} |
|
572 |
if (complete) |
|
573 |
throw new IllegalStateException("Closed"); |
|
574 |
else |
|
575 |
return (drops > 0) ? -drops : lag; |
|
576 |
} |
|
577 |
||
578 |
/** |
|
579 |
* Unless already closed, issues {@link |
|
580 |
* Flow.Subscriber#onComplete() onComplete} signals to current |
|
581 |
* subscribers, and disallows subsequent attempts to publish. |
|
582 |
* Upon return, this method does <em>NOT</em> guarantee that all |
|
583 |
* subscribers have yet completed. |
|
584 |
*/ |
|
585 |
public void close() { |
|
586 |
if (!closed) { |
|
587 |
BufferedSubscription<T> b; |
|
588 |
synchronized (this) { |
|
589 |
b = clients; |
|
590 |
clients = null; |
|
591 |
closed = true; |
|
592 |
} |
|
593 |
while (b != null) { |
|
594 |
BufferedSubscription<T> next = b.next; |
|
595 |
b.next = null; |
|
596 |
b.onComplete(); |
|
597 |
b = next; |
|
598 |
} |
|
599 |
} |
|
600 |
} |
|
601 |
||
602 |
/** |
|
603 |
* Unless already closed, issues {@link |
|
604 |
* Flow.Subscriber#onError(Throwable) onError} signals to current |
|
605 |
* subscribers with the given error, and disallows subsequent |
|
606 |
* attempts to publish. Future subscribers also receive the given |
|
607 |
* error. Upon return, this method does <em>NOT</em> guarantee |
|
608 |
* that all subscribers have yet completed. |
|
609 |
* |
|
610 |
* @param error the {@code onError} argument sent to subscribers |
|
611 |
* @throws NullPointerException if error is null |
|
612 |
*/ |
|
613 |
public void closeExceptionally(Throwable error) { |
|
614 |
if (error == null) |
|
615 |
throw new NullPointerException(); |
|
616 |
if (!closed) { |
|
617 |
BufferedSubscription<T> b; |
|
618 |
synchronized (this) { |
|
619 |
b = clients; |
|
620 |
clients = null; |
|
621 |
closed = true; |
|
622 |
closedException = error; |
|
623 |
} |
|
624 |
while (b != null) { |
|
625 |
BufferedSubscription<T> next = b.next; |
|
626 |
b.next = null; |
|
627 |
b.onError(error); |
|
628 |
b = next; |
|
629 |
} |
|
630 |
} |
|
631 |
} |
|
632 |
||
633 |
/** |
|
634 |
* Returns true if this publisher is not accepting submissions. |
|
635 |
* |
|
636 |
* @return true if closed |
|
637 |
*/ |
|
638 |
public boolean isClosed() { |
|
639 |
return closed; |
|
640 |
} |
|
641 |
||
642 |
/** |
|
643 |
* Returns the exception associated with {@link |
|
644 |
* #closeExceptionally(Throwable) closeExceptionally}, or null if |
|
645 |
* not closed or if closed normally. |
|
646 |
* |
|
647 |
* @return the exception, or null if none |
|
648 |
*/ |
|
649 |
public Throwable getClosedException() { |
|
650 |
return closedException; |
|
651 |
} |
|
652 |
||
653 |
/** |
|
654 |
* Returns true if this publisher has any subscribers. |
|
655 |
* |
|
656 |
* @return true if this publisher has any subscribers |
|
657 |
*/ |
|
658 |
public boolean hasSubscribers() { |
|
659 |
boolean nonEmpty = false; |
|
660 |
if (!closed) { |
|
661 |
synchronized (this) { |
|
662 |
for (BufferedSubscription<T> b = clients; b != null;) { |
|
663 |
BufferedSubscription<T> next = b.next; |
|
664 |
if (b.isDisabled()) { |
|
665 |
b.next = null; |
|
666 |
b = clients = next; |
|
667 |
} |
|
668 |
else { |
|
669 |
nonEmpty = true; |
|
670 |
break; |
|
671 |
} |
|
672 |
} |
|
673 |
} |
|
674 |
} |
|
675 |
return nonEmpty; |
|
676 |
} |
|
677 |
||
678 |
/** |
|
679 |
* Returns the number of current subscribers. |
|
680 |
* |
|
681 |
* @return the number of current subscribers |
|
682 |
*/ |
|
683 |
public int getNumberOfSubscribers() { |
|
684 |
int count = 0; |
|
685 |
if (!closed) { |
|
686 |
synchronized (this) { |
|
687 |
BufferedSubscription<T> pred = null, next; |
|
688 |
for (BufferedSubscription<T> b = clients; b != null; b = next) { |
|
689 |
next = b.next; |
|
690 |
if (b.isDisabled()) { |
|
691 |
b.next = null; |
|
692 |
if (pred == null) |
|
693 |
clients = next; |
|
694 |
else |
|
695 |
pred.next = next; |
|
696 |
} |
|
697 |
else { |
|
698 |
pred = b; |
|
699 |
++count; |
|
700 |
} |
|
701 |
} |
|
702 |
} |
|
703 |
} |
|
704 |
return count; |
|
705 |
} |
|
706 |
||
707 |
/** |
|
708 |
* Returns the Executor used for asynchronous delivery. |
|
709 |
* |
|
710 |
* @return the Executor used for asynchronous delivery |
|
711 |
*/ |
|
712 |
public Executor getExecutor() { |
|
713 |
return executor; |
|
714 |
} |
|
715 |
||
716 |
/** |
|
717 |
* Returns the maximum per-subscriber buffer capacity. |
|
718 |
* |
|
719 |
* @return the maximum per-subscriber buffer capacity |
|
720 |
*/ |
|
721 |
public int getMaxBufferCapacity() { |
|
722 |
return maxBufferCapacity; |
|
723 |
} |
|
724 |
||
725 |
/** |
|
726 |
* Returns a list of current subscribers for monitoring and |
|
727 |
* tracking purposes, not for invoking {@link Flow.Subscriber} |
|
728 |
* methods on the subscribers. |
|
729 |
* |
|
730 |
* @return list of current subscribers |
|
731 |
*/ |
|
732 |
public List<Flow.Subscriber<? super T>> getSubscribers() { |
|
733 |
ArrayList<Flow.Subscriber<? super T>> subs = new ArrayList<>(); |
|
734 |
synchronized (this) { |
|
735 |
BufferedSubscription<T> pred = null, next; |
|
736 |
for (BufferedSubscription<T> b = clients; b != null; b = next) { |
|
737 |
next = b.next; |
|
738 |
if (b.isDisabled()) { |
|
739 |
b.next = null; |
|
740 |
if (pred == null) |
|
741 |
clients = next; |
|
742 |
else |
|
743 |
pred.next = next; |
|
744 |
} |
|
745 |
else |
|
746 |
subs.add(b.subscriber); |
|
747 |
} |
|
748 |
} |
|
749 |
return subs; |
|
750 |
} |
|
751 |
||
752 |
/** |
|
753 |
* Returns true if the given Subscriber is currently subscribed. |
|
754 |
* |
|
755 |
* @param subscriber the subscriber |
|
756 |
* @return true if currently subscribed |
|
757 |
* @throws NullPointerException if subscriber is null |
|
758 |
*/ |
|
759 |
public boolean isSubscribed(Flow.Subscriber<? super T> subscriber) { |
|
760 |
if (subscriber == null) throw new NullPointerException(); |
|
761 |
if (!closed) { |
|
762 |
synchronized (this) { |
|
763 |
BufferedSubscription<T> pred = null, next; |
|
764 |
for (BufferedSubscription<T> b = clients; b != null; b = next) { |
|
765 |
next = b.next; |
|
766 |
if (b.isDisabled()) { |
|
767 |
b.next = null; |
|
768 |
if (pred == null) |
|
769 |
clients = next; |
|
770 |
else |
|
771 |
pred.next = next; |
|
772 |
} |
|
773 |
else if (subscriber.equals(b.subscriber)) |
|
774 |
return true; |
|
775 |
else |
|
776 |
pred = b; |
|
777 |
} |
|
778 |
} |
|
779 |
} |
|
780 |
return false; |
|
781 |
} |
|
782 |
||
783 |
/** |
|
784 |
* Returns an estimate of the minimum number of items requested |
|
785 |
* (via {@link Flow.Subscription#request(long) request}) but not |
|
786 |
* yet produced, among all current subscribers. |
|
787 |
* |
|
788 |
* @return the estimate, or zero if no subscribers |
|
789 |
*/ |
|
790 |
public long estimateMinimumDemand() { |
|
791 |
long min = Long.MAX_VALUE; |
|
792 |
boolean nonEmpty = false; |
|
793 |
synchronized (this) { |
|
794 |
BufferedSubscription<T> pred = null, next; |
|
795 |
for (BufferedSubscription<T> b = clients; b != null; b = next) { |
|
796 |
int n; long d; |
|
797 |
next = b.next; |
|
798 |
if ((n = b.estimateLag()) < 0) { |
|
799 |
b.next = null; |
|
800 |
if (pred == null) |
|
801 |
clients = next; |
|
802 |
else |
|
803 |
pred.next = next; |
|
804 |
} |
|
805 |
else { |
|
806 |
if ((d = b.demand - n) < min) |
|
807 |
min = d; |
|
808 |
nonEmpty = true; |
|
809 |
pred = b; |
|
810 |
} |
|
811 |
} |
|
812 |
} |
|
813 |
return nonEmpty ? min : 0; |
|
814 |
} |
|
815 |
||
816 |
/** |
|
817 |
* Returns an estimate of the maximum number of items produced but |
|
818 |
* not yet consumed among all current subscribers. |
|
819 |
* |
|
820 |
* @return the estimate |
|
821 |
*/ |
|
822 |
public int estimateMaximumLag() { |
|
823 |
int max = 0; |
|
824 |
synchronized (this) { |
|
825 |
BufferedSubscription<T> pred = null, next; |
|
826 |
for (BufferedSubscription<T> b = clients; b != null; b = next) { |
|
827 |
int n; |
|
828 |
next = b.next; |
|
829 |
if ((n = b.estimateLag()) < 0) { |
|
830 |
b.next = null; |
|
831 |
if (pred == null) |
|
832 |
clients = next; |
|
833 |
else |
|
834 |
pred.next = next; |
|
835 |
} |
|
836 |
else { |
|
837 |
if (n > max) |
|
838 |
max = n; |
|
839 |
pred = b; |
|
840 |
} |
|
841 |
} |
|
842 |
} |
|
843 |
return max; |
|
844 |
} |
|
845 |
||
846 |
/** |
|
847 |
* Processes all published items using the given Consumer function. |
|
848 |
* Returns a CompletableFuture that is completed normally when this |
|
849 |
* publisher signals {@link Flow.Subscriber#onComplete() |
|
850 |
* onComplete}, or completed exceptionally upon any error, or an |
|
851 |
* exception is thrown by the Consumer, or the returned |
|
852 |
* CompletableFuture is cancelled, in which case no further items |
|
853 |
* are processed. |
|
854 |
* |
|
855 |
* @param consumer the function applied to each onNext item |
|
856 |
* @return a CompletableFuture that is completed normally |
|
857 |
* when the publisher signals onComplete, and exceptionally |
|
858 |
* upon any error or cancellation |
|
859 |
* @throws NullPointerException if consumer is null |
|
860 |
*/ |
|
861 |
public CompletableFuture<Void> consume(Consumer<? super T> consumer) { |
|
862 |
if (consumer == null) |
|
863 |
throw new NullPointerException(); |
|
864 |
CompletableFuture<Void> status = new CompletableFuture<>(); |
|
865 |
subscribe(new ConsumerSubscriber<T>(status, consumer)); |
|
866 |
return status; |
|
867 |
} |
|
868 |
||
869 |
/** Subscriber for method consume */ |
|
870 |
private static final class ConsumerSubscriber<T> |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
871 |
implements Flow.Subscriber<T> { |
32989 | 872 |
final CompletableFuture<Void> status; |
873 |
final Consumer<? super T> consumer; |
|
874 |
Flow.Subscription subscription; |
|
875 |
ConsumerSubscriber(CompletableFuture<Void> status, |
|
876 |
Consumer<? super T> consumer) { |
|
877 |
this.status = status; this.consumer = consumer; |
|
878 |
} |
|
879 |
public final void onSubscribe(Flow.Subscription subscription) { |
|
880 |
this.subscription = subscription; |
|
881 |
status.whenComplete((v, e) -> subscription.cancel()); |
|
882 |
if (!status.isDone()) |
|
883 |
subscription.request(Long.MAX_VALUE); |
|
884 |
} |
|
885 |
public final void onError(Throwable ex) { |
|
886 |
status.completeExceptionally(ex); |
|
887 |
} |
|
888 |
public final void onComplete() { |
|
889 |
status.complete(null); |
|
890 |
} |
|
891 |
public final void onNext(T item) { |
|
892 |
try { |
|
893 |
consumer.accept(item); |
|
894 |
} catch (Throwable ex) { |
|
895 |
subscription.cancel(); |
|
896 |
status.completeExceptionally(ex); |
|
897 |
} |
|
898 |
} |
|
899 |
} |
|
900 |
||
901 |
/** |
|
902 |
* A task for consuming buffer items and signals, created and |
|
903 |
* executed whenever they become available. A task consumes as |
|
904 |
* many items/signals as possible before terminating, at which |
|
905 |
* point another task is created when needed. The dual Runnable |
|
906 |
* and ForkJoinTask declaration saves overhead when executed by |
|
907 |
* ForkJoinPools, without impacting other kinds of Executors. |
|
908 |
*/ |
|
909 |
@SuppressWarnings("serial") |
|
910 |
static final class ConsumerTask<T> extends ForkJoinTask<Void> |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
911 |
implements Runnable, CompletableFuture.AsynchronousCompletionTask { |
32989 | 912 |
final BufferedSubscription<T> consumer; |
913 |
ConsumerTask(BufferedSubscription<T> consumer) { |
|
914 |
this.consumer = consumer; |
|
915 |
} |
|
916 |
public final Void getRawResult() { return null; } |
|
917 |
public final void setRawResult(Void v) {} |
|
918 |
public final boolean exec() { consumer.consume(); return false; } |
|
919 |
public final void run() { consumer.consume(); } |
|
920 |
} |
|
921 |
||
922 |
/** |
|
923 |
* A bounded (ring) buffer with integrated control to start a |
|
924 |
* consumer task whenever items are available. The buffer |
|
925 |
* algorithm is similar to one used inside ForkJoinPool (see its |
|
926 |
* internal documentation for details) specialized for the case of |
|
927 |
* at most one concurrent producer and consumer, and power of two |
|
928 |
* buffer sizes. This allows methods to operate without locks even |
|
929 |
* while supporting resizing, blocking, task-triggering, and |
|
930 |
* garbage-free buffers (nulling out elements when consumed), |
|
931 |
* although supporting these does impose a bit of overhead |
|
932 |
* compared to plain fixed-size ring buffers. |
|
933 |
* |
|
934 |
* The publisher guarantees a single producer via its lock. We |
|
935 |
* ensure in this class that there is at most one consumer. The |
|
936 |
* request and cancel methods must be fully thread-safe but are |
|
937 |
* coded to exploit the most common case in which they are only |
|
938 |
* called by consumers (usually within onNext). |
|
939 |
* |
|
940 |
* Execution control is managed using the ACTIVE ctl bit. We |
|
941 |
* ensure that a task is active when consumable items (and |
|
942 |
* usually, SUBSCRIBE, ERROR or COMPLETE signals) are present and |
|
943 |
* there is demand (unfilled requests). This is complicated on |
|
944 |
* the creation side by the possibility of exceptions when trying |
|
945 |
* to execute tasks. These eventually force DISABLED state, but |
|
946 |
* sometimes not directly. On the task side, termination (clearing |
|
947 |
* ACTIVE) that would otherwise race with producers or request() |
|
948 |
* calls uses the CONSUME keep-alive bit to force a recheck. |
|
949 |
* |
|
950 |
* The ctl field also manages run state. When DISABLED, no further |
|
951 |
* updates are possible. Disabling may be preceded by setting |
|
952 |
* ERROR or COMPLETE (or both -- ERROR has precedence), in which |
|
953 |
* case the associated Subscriber methods are invoked, possibly |
|
954 |
* synchronously if there is no active consumer task (including |
|
955 |
* cases where execute() failed). The cancel() method is supported |
|
956 |
* by treating as ERROR but suppressing onError signal. |
|
957 |
* |
|
958 |
* Support for blocking also exploits the fact that there is only |
|
959 |
* one possible waiter. ManagedBlocker-compatible control fields |
|
960 |
* are placed in this class itself rather than in wait-nodes. |
|
961 |
* Blocking control relies on the "waiter" field. Producers set |
|
962 |
* the field before trying to block, but must then recheck (via |
|
963 |
* offer) before parking. Signalling then just unparks and clears |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
964 |
* waiter field. If the producer and/or consumer are using a |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
965 |
* ForkJoinPool, the producer attempts to help run consumer tasks |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
966 |
* via ForkJoinPool.helpAsyncBlocker before blocking. |
32989 | 967 |
* |
968 |
* This class uses @Contended and heuristic field declaration |
|
969 |
* ordering to reduce false-sharing-based memory contention among |
|
970 |
* instances of BufferedSubscription, but it does not currently |
|
971 |
* attempt to avoid memory contention among buffers. This field |
|
972 |
* and element packing can hurt performance especially when each |
|
973 |
* publisher has only one client operating at a high rate. |
|
974 |
* Addressing this may require allocating substantially more space |
|
975 |
* than users expect. |
|
976 |
*/ |
|
977 |
@SuppressWarnings("serial") |
|
34369
b6df4cc80001
8140687: Move @Contended to the jdk.internal.vm.annotation package
chegar
parents:
33674
diff
changeset
|
978 |
@jdk.internal.vm.annotation.Contended |
32989 | 979 |
private static final class BufferedSubscription<T> |
980 |
implements Flow.Subscription, ForkJoinPool.ManagedBlocker { |
|
981 |
// Order-sensitive field declarations |
|
982 |
long timeout; // > 0 if timed wait |
|
983 |
volatile long demand; // # unfilled requests |
|
984 |
int maxCapacity; // reduced on OOME |
|
985 |
int putStat; // offer result for ManagedBlocker |
|
986 |
volatile int ctl; // atomic run state flags |
|
987 |
volatile int head; // next position to take |
|
988 |
int tail; // next position to put |
|
989 |
Object[] array; // buffer: null if disabled |
|
990 |
Flow.Subscriber<? super T> subscriber; // null if disabled |
|
991 |
Executor executor; // null if disabled |
|
992 |
BiConsumer<? super Flow.Subscriber<? super T>, ? super Throwable> onNextHandler; |
|
993 |
volatile Throwable pendingError; // holds until onError issued |
|
994 |
volatile Thread waiter; // blocked producer thread |
|
995 |
T putItem; // for offer within ManagedBlocker |
|
996 |
BufferedSubscription<T> next; // used only by publisher |
|
997 |
BufferedSubscription<T> nextRetry; // used only by publisher |
|
998 |
||
999 |
// ctl values |
|
1000 |
static final int ACTIVE = 0x01; // consumer task active |
|
1001 |
static final int CONSUME = 0x02; // keep-alive for consumer task |
|
1002 |
static final int DISABLED = 0x04; // final state |
|
1003 |
static final int ERROR = 0x08; // signal onError then disable |
|
1004 |
static final int SUBSCRIBE = 0x10; // signal onSubscribe |
|
1005 |
static final int COMPLETE = 0x20; // signal onComplete when done |
|
1006 |
||
1007 |
static final long INTERRUPTED = -1L; // timeout vs interrupt sentinel |
|
1008 |
||
1009 |
/** |
|
1010 |
* Initial buffer capacity used when maxBufferCapacity is |
|
1011 |
* greater. Must be a power of two. |
|
1012 |
*/ |
|
1013 |
static final int DEFAULT_INITIAL_CAP = 32; |
|
1014 |
||
1015 |
BufferedSubscription(Flow.Subscriber<? super T> subscriber, |
|
1016 |
Executor executor, |
|
1017 |
BiConsumer<? super Flow.Subscriber<? super T>, |
|
1018 |
? super Throwable> onNextHandler, |
|
1019 |
int maxBufferCapacity) { |
|
1020 |
this.subscriber = subscriber; |
|
1021 |
this.executor = executor; |
|
1022 |
this.onNextHandler = onNextHandler; |
|
1023 |
this.maxCapacity = maxBufferCapacity; |
|
1024 |
this.array = new Object[maxBufferCapacity < DEFAULT_INITIAL_CAP ? |
|
1025 |
(maxBufferCapacity < 2 ? // at least 2 slots |
|
1026 |
2 : maxBufferCapacity) : |
|
1027 |
DEFAULT_INITIAL_CAP]; |
|
1028 |
} |
|
1029 |
||
1030 |
final boolean isDisabled() { |
|
1031 |
return ctl == DISABLED; |
|
1032 |
} |
|
1033 |
||
1034 |
/** |
|
1035 |
* Returns estimated number of buffered items, or -1 if |
|
1036 |
* disabled. |
|
1037 |
*/ |
|
1038 |
final int estimateLag() { |
|
1039 |
int n; |
|
1040 |
return (ctl == DISABLED) ? -1 : ((n = tail - head) > 0) ? n : 0; |
|
1041 |
} |
|
1042 |
||
1043 |
/** |
|
1044 |
* Tries to add item and start consumer task if necessary. |
|
1045 |
* @return -1 if disabled, 0 if dropped, else estimated lag |
|
1046 |
*/ |
|
1047 |
final int offer(T item) { |
|
1048 |
int h = head, t = tail, cap, size, stat; |
|
1049 |
Object[] a = array; |
|
1050 |
if (a != null && (cap = a.length) > 0 && cap >= (size = t + 1 - h)) { |
|
1051 |
a[(cap - 1) & t] = item; // relaxed writes OK |
|
1052 |
tail = t + 1; |
|
1053 |
stat = size; |
|
1054 |
} |
|
1055 |
else |
|
1056 |
stat = growAndAdd(a, item); |
|
1057 |
return (stat > 0 && |
|
1058 |
(ctl & (ACTIVE | CONSUME)) != (ACTIVE | CONSUME)) ? |
|
1059 |
startOnOffer(stat) : stat; |
|
1060 |
} |
|
1061 |
||
1062 |
/** |
|
1063 |
* Tries to create or expand buffer, then adds item if possible. |
|
1064 |
*/ |
|
1065 |
private int growAndAdd(Object[] a, T item) { |
|
1066 |
boolean alloc; |
|
1067 |
int cap, stat; |
|
1068 |
if ((ctl & (ERROR | DISABLED)) != 0) { |
|
1069 |
cap = 0; |
|
1070 |
stat = -1; |
|
1071 |
alloc = false; |
|
1072 |
} |
|
1073 |
else if (a == null || (cap = a.length) <= 0) { |
|
1074 |
cap = 0; |
|
1075 |
stat = 1; |
|
1076 |
alloc = true; |
|
1077 |
} |
|
1078 |
else { |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1079 |
VarHandle.fullFence(); // recheck |
32989 | 1080 |
int h = head, t = tail, size = t + 1 - h; |
1081 |
if (cap >= size) { |
|
1082 |
a[(cap - 1) & t] = item; |
|
1083 |
tail = t + 1; |
|
1084 |
stat = size; |
|
1085 |
alloc = false; |
|
1086 |
} |
|
1087 |
else if (cap >= maxCapacity) { |
|
1088 |
stat = 0; // cannot grow |
|
1089 |
alloc = false; |
|
1090 |
} |
|
1091 |
else { |
|
1092 |
stat = cap + 1; |
|
1093 |
alloc = true; |
|
1094 |
} |
|
1095 |
} |
|
1096 |
if (alloc) { |
|
1097 |
int newCap = (cap > 0) ? cap << 1 : 1; |
|
1098 |
if (newCap <= cap) |
|
1099 |
stat = 0; |
|
1100 |
else { |
|
1101 |
Object[] newArray = null; |
|
1102 |
try { |
|
1103 |
newArray = new Object[newCap]; |
|
1104 |
} catch (Throwable ex) { // try to cope with OOME |
|
1105 |
} |
|
1106 |
if (newArray == null) { |
|
1107 |
if (cap > 0) |
|
1108 |
maxCapacity = cap; // avoid continuous failure |
|
1109 |
stat = 0; |
|
1110 |
} |
|
1111 |
else { |
|
1112 |
array = newArray; |
|
1113 |
int t = tail; |
|
1114 |
int newMask = newCap - 1; |
|
1115 |
if (a != null && cap > 0) { |
|
1116 |
int mask = cap - 1; |
|
1117 |
for (int j = head; j != t; ++j) { |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1118 |
int k = j & mask; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1119 |
Object x = QA.getAcquire(a, k); |
32989 | 1120 |
if (x != null && // races with consumer |
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1121 |
QA.compareAndSet(a, k, x, null)) |
32989 | 1122 |
newArray[j & newMask] = x; |
1123 |
} |
|
1124 |
} |
|
1125 |
newArray[t & newMask] = item; |
|
1126 |
tail = t + 1; |
|
1127 |
} |
|
1128 |
} |
|
1129 |
} |
|
1130 |
return stat; |
|
1131 |
} |
|
1132 |
||
1133 |
/** |
|
1134 |
* Spins/helps/blocks while offer returns 0. Called only if |
|
1135 |
* initial offer return 0. |
|
1136 |
*/ |
|
1137 |
final int submit(T item) { |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1138 |
int stat; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1139 |
if ((stat = offer(item)) == 0) { |
32989 | 1140 |
putItem = item; |
1141 |
timeout = 0L; |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1142 |
putStat = 0; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1143 |
ForkJoinPool.helpAsyncBlocker(executor, this); |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1144 |
if ((stat = putStat) == 0) { |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1145 |
try { |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1146 |
ForkJoinPool.managedBlock(this); |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1147 |
} catch (InterruptedException ie) { |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1148 |
timeout = INTERRUPTED; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1149 |
} |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1150 |
stat = putStat; |
32989 | 1151 |
} |
1152 |
if (timeout < 0L) |
|
1153 |
Thread.currentThread().interrupt(); |
|
1154 |
} |
|
1155 |
return stat; |
|
1156 |
} |
|
1157 |
||
1158 |
/** |
|
1159 |
* Timeout version; similar to submit. |
|
1160 |
*/ |
|
1161 |
final int timedOffer(T item, long nanos) { |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1162 |
int stat; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1163 |
if ((stat = offer(item)) == 0 && (timeout = nanos) > 0L) { |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1164 |
putItem = item; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1165 |
putStat = 0; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1166 |
ForkJoinPool.helpAsyncBlocker(executor, this); |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1167 |
if ((stat = putStat) == 0) { |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1168 |
try { |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1169 |
ForkJoinPool.managedBlock(this); |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1170 |
} catch (InterruptedException ie) { |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1171 |
timeout = INTERRUPTED; |
32989 | 1172 |
} |
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1173 |
stat = putStat; |
32989 | 1174 |
} |
1175 |
if (timeout < 0L) |
|
1176 |
Thread.currentThread().interrupt(); |
|
1177 |
} |
|
1178 |
return stat; |
|
1179 |
} |
|
1180 |
||
1181 |
/** |
|
1182 |
* Tries to start consumer task after offer. |
|
1183 |
* @return -1 if now disabled, else argument |
|
1184 |
*/ |
|
1185 |
private int startOnOffer(int stat) { |
|
1186 |
for (;;) { |
|
1187 |
Executor e; int c; |
|
1188 |
if ((c = ctl) == DISABLED || (e = executor) == null) { |
|
1189 |
stat = -1; |
|
1190 |
break; |
|
1191 |
} |
|
1192 |
else if ((c & ACTIVE) != 0) { // ensure keep-alive |
|
1193 |
if ((c & CONSUME) != 0 || |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1194 |
CTL.compareAndSet(this, c, c | CONSUME)) |
32989 | 1195 |
break; |
1196 |
} |
|
1197 |
else if (demand == 0L || tail == head) |
|
1198 |
break; |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1199 |
else if (CTL.compareAndSet(this, c, c | (ACTIVE | CONSUME))) { |
32989 | 1200 |
try { |
1201 |
e.execute(new ConsumerTask<T>(this)); |
|
1202 |
break; |
|
1203 |
} catch (RuntimeException | Error ex) { // back out |
|
1204 |
do {} while (((c = ctl) & DISABLED) == 0 && |
|
1205 |
(c & ACTIVE) != 0 && |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1206 |
!CTL.weakCompareAndSetVolatile |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1207 |
(this, c, c & ~ACTIVE)); |
32989 | 1208 |
throw ex; |
1209 |
} |
|
1210 |
} |
|
1211 |
} |
|
1212 |
return stat; |
|
1213 |
} |
|
1214 |
||
1215 |
private void signalWaiter(Thread w) { |
|
1216 |
waiter = null; |
|
1217 |
LockSupport.unpark(w); // release producer |
|
1218 |
} |
|
1219 |
||
1220 |
/** |
|
1221 |
* Nulls out most fields, mainly to avoid garbage retention |
|
1222 |
* until publisher unsubscribes, but also to help cleanly stop |
|
1223 |
* upon error by nulling required components. |
|
1224 |
*/ |
|
1225 |
private void detach() { |
|
1226 |
Thread w = waiter; |
|
1227 |
executor = null; |
|
1228 |
subscriber = null; |
|
1229 |
pendingError = null; |
|
1230 |
signalWaiter(w); |
|
1231 |
} |
|
1232 |
||
1233 |
/** |
|
1234 |
* Issues error signal, asynchronously if a task is running, |
|
1235 |
* else synchronously. |
|
1236 |
*/ |
|
1237 |
final void onError(Throwable ex) { |
|
1238 |
for (int c;;) { |
|
1239 |
if (((c = ctl) & (ERROR | DISABLED)) != 0) |
|
1240 |
break; |
|
1241 |
else if ((c & ACTIVE) != 0) { |
|
1242 |
pendingError = ex; |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1243 |
if (CTL.compareAndSet(this, c, c | ERROR)) |
32989 | 1244 |
break; // cause consumer task to exit |
1245 |
} |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1246 |
else if (CTL.compareAndSet(this, c, DISABLED)) { |
32989 | 1247 |
Flow.Subscriber<? super T> s = subscriber; |
1248 |
if (s != null && ex != null) { |
|
1249 |
try { |
|
1250 |
s.onError(ex); |
|
1251 |
} catch (Throwable ignore) { |
|
1252 |
} |
|
1253 |
} |
|
1254 |
detach(); |
|
1255 |
break; |
|
1256 |
} |
|
1257 |
} |
|
1258 |
} |
|
1259 |
||
1260 |
/** |
|
1261 |
* Tries to start consumer task upon a signal or request; |
|
1262 |
* disables on failure. |
|
1263 |
*/ |
|
1264 |
private void startOrDisable() { |
|
1265 |
Executor e; |
|
1266 |
if ((e = executor) != null) { // skip if already disabled |
|
1267 |
try { |
|
1268 |
e.execute(new ConsumerTask<T>(this)); |
|
1269 |
} catch (Throwable ex) { // back out and force signal |
|
1270 |
for (int c;;) { |
|
1271 |
if ((c = ctl) == DISABLED || (c & ACTIVE) == 0) |
|
1272 |
break; |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1273 |
if (CTL.compareAndSet(this, c, c & ~ACTIVE)) { |
32989 | 1274 |
onError(ex); |
1275 |
break; |
|
1276 |
} |
|
1277 |
} |
|
1278 |
} |
|
1279 |
} |
|
1280 |
} |
|
1281 |
||
1282 |
final void onComplete() { |
|
1283 |
for (int c;;) { |
|
1284 |
if ((c = ctl) == DISABLED) |
|
1285 |
break; |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1286 |
if (CTL.compareAndSet(this, c, |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1287 |
c | (ACTIVE | CONSUME | COMPLETE))) { |
32989 | 1288 |
if ((c & ACTIVE) == 0) |
1289 |
startOrDisable(); |
|
1290 |
break; |
|
1291 |
} |
|
1292 |
} |
|
1293 |
} |
|
1294 |
||
1295 |
final void onSubscribe() { |
|
1296 |
for (int c;;) { |
|
1297 |
if ((c = ctl) == DISABLED) |
|
1298 |
break; |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1299 |
if (CTL.compareAndSet(this, c, |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1300 |
c | (ACTIVE | CONSUME | SUBSCRIBE))) { |
32989 | 1301 |
if ((c & ACTIVE) == 0) |
1302 |
startOrDisable(); |
|
1303 |
break; |
|
1304 |
} |
|
1305 |
} |
|
1306 |
} |
|
1307 |
||
1308 |
/** |
|
1309 |
* Causes consumer task to exit if active (without reporting |
|
1310 |
* onError unless there is already a pending error), and |
|
1311 |
* disables. |
|
1312 |
*/ |
|
1313 |
public void cancel() { |
|
1314 |
for (int c;;) { |
|
1315 |
if ((c = ctl) == DISABLED) |
|
1316 |
break; |
|
1317 |
else if ((c & ACTIVE) != 0) { |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1318 |
if (CTL.compareAndSet(this, c, |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1319 |
c | (CONSUME | ERROR))) |
32989 | 1320 |
break; |
1321 |
} |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1322 |
else if (CTL.compareAndSet(this, c, DISABLED)) { |
32989 | 1323 |
detach(); |
1324 |
break; |
|
1325 |
} |
|
1326 |
} |
|
1327 |
} |
|
1328 |
||
1329 |
/** |
|
1330 |
* Adds to demand and possibly starts task. |
|
1331 |
*/ |
|
1332 |
public void request(long n) { |
|
1333 |
if (n > 0L) { |
|
1334 |
for (;;) { |
|
1335 |
long prev = demand, d; |
|
1336 |
if ((d = prev + n) < prev) // saturate |
|
1337 |
d = Long.MAX_VALUE; |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1338 |
if (DEMAND.compareAndSet(this, prev, d)) { |
32989 | 1339 |
for (int c, h;;) { |
1340 |
if ((c = ctl) == DISABLED) |
|
1341 |
break; |
|
1342 |
else if ((c & ACTIVE) != 0) { |
|
1343 |
if ((c & CONSUME) != 0 || |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1344 |
CTL.compareAndSet(this, c, c | CONSUME)) |
32989 | 1345 |
break; |
1346 |
} |
|
1347 |
else if ((h = head) != tail) { |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1348 |
if (CTL.compareAndSet(this, c, |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1349 |
c | (ACTIVE|CONSUME))) { |
32989 | 1350 |
startOrDisable(); |
1351 |
break; |
|
1352 |
} |
|
1353 |
} |
|
1354 |
else if (head == h && tail == h) |
|
1355 |
break; // else stale |
|
1356 |
if (demand == 0L) |
|
1357 |
break; |
|
1358 |
} |
|
1359 |
break; |
|
1360 |
} |
|
1361 |
} |
|
1362 |
} |
|
1363 |
else if (n < 0L) |
|
1364 |
onError(new IllegalArgumentException( |
|
1365 |
"negative subscription request")); |
|
1366 |
} |
|
1367 |
||
1368 |
public final boolean isReleasable() { // for ManagedBlocker |
|
1369 |
T item = putItem; |
|
1370 |
if (item != null) { |
|
1371 |
if ((putStat = offer(item)) == 0) |
|
1372 |
return false; |
|
1373 |
putItem = null; |
|
1374 |
} |
|
1375 |
return true; |
|
1376 |
} |
|
1377 |
||
1378 |
public final boolean block() { // for ManagedBlocker |
|
1379 |
T item = putItem; |
|
1380 |
if (item != null) { |
|
1381 |
putItem = null; |
|
1382 |
long nanos = timeout; |
|
1383 |
long deadline = (nanos > 0L) ? System.nanoTime() + nanos : 0L; |
|
1384 |
while ((putStat = offer(item)) == 0) { |
|
1385 |
if (Thread.interrupted()) { |
|
1386 |
timeout = INTERRUPTED; |
|
1387 |
if (nanos > 0L) |
|
1388 |
break; |
|
1389 |
} |
|
1390 |
else if (nanos > 0L && |
|
1391 |
(nanos = deadline - System.nanoTime()) <= 0L) |
|
1392 |
break; |
|
1393 |
else if (waiter == null) |
|
1394 |
waiter = Thread.currentThread(); |
|
1395 |
else { |
|
1396 |
if (nanos > 0L) |
|
1397 |
LockSupport.parkNanos(this, nanos); |
|
1398 |
else |
|
1399 |
LockSupport.park(this); |
|
1400 |
waiter = null; |
|
1401 |
} |
|
1402 |
} |
|
1403 |
} |
|
1404 |
waiter = null; |
|
1405 |
return true; |
|
1406 |
} |
|
1407 |
||
1408 |
/** |
|
1409 |
* Consumer loop, called from ConsumerTask, or indirectly |
|
1410 |
* when helping during submit. |
|
1411 |
*/ |
|
1412 |
final void consume() { |
|
1413 |
Flow.Subscriber<? super T> s; |
|
1414 |
int h = head; |
|
1415 |
if ((s = subscriber) != null) { // else disabled |
|
1416 |
for (;;) { |
|
1417 |
long d = demand; |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1418 |
int c; Object[] a; int n, i; Object x; Thread w; |
32989 | 1419 |
if (((c = ctl) & (ERROR | SUBSCRIBE | DISABLED)) != 0) { |
1420 |
if (!checkControl(s, c)) |
|
1421 |
break; |
|
1422 |
} |
|
1423 |
else if ((a = array) == null || h == tail || |
|
1424 |
(n = a.length) == 0 || |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1425 |
(x = QA.getAcquire(a, i = (n - 1) & h)) == null) { |
32989 | 1426 |
if (!checkEmpty(s, c)) |
1427 |
break; |
|
1428 |
} |
|
1429 |
else if (d == 0L) { |
|
1430 |
if (!checkDemand(c)) |
|
1431 |
break; |
|
1432 |
} |
|
1433 |
else if (((c & CONSUME) != 0 || |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1434 |
CTL.compareAndSet(this, c, c | CONSUME)) && |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1435 |
QA.compareAndSet(a, i, x, null)) { |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1436 |
HEAD.setRelease(this, ++h); |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1437 |
DEMAND.getAndAdd(this, -1L); |
32989 | 1438 |
if ((w = waiter) != null) |
1439 |
signalWaiter(w); |
|
1440 |
try { |
|
1441 |
@SuppressWarnings("unchecked") T y = (T) x; |
|
1442 |
s.onNext(y); |
|
1443 |
} catch (Throwable ex) { |
|
1444 |
handleOnNext(s, ex); |
|
1445 |
} |
|
1446 |
} |
|
1447 |
} |
|
1448 |
} |
|
1449 |
} |
|
1450 |
||
1451 |
/** |
|
1452 |
* Responds to control events in consume(). |
|
1453 |
*/ |
|
1454 |
private boolean checkControl(Flow.Subscriber<? super T> s, int c) { |
|
1455 |
boolean stat = true; |
|
1456 |
if ((c & ERROR) != 0) { |
|
1457 |
Throwable ex = pendingError; |
|
1458 |
ctl = DISABLED; // no need for CAS |
|
1459 |
if (ex != null) { // null if errorless cancel |
|
1460 |
try { |
|
1461 |
if (s != null) |
|
1462 |
s.onError(ex); |
|
1463 |
} catch (Throwable ignore) { |
|
1464 |
} |
|
1465 |
} |
|
1466 |
} |
|
1467 |
else if ((c & SUBSCRIBE) != 0) { |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1468 |
if (CTL.compareAndSet(this, c, c & ~SUBSCRIBE)) { |
32989 | 1469 |
try { |
1470 |
if (s != null) |
|
1471 |
s.onSubscribe(this); |
|
1472 |
} catch (Throwable ex) { |
|
1473 |
onError(ex); |
|
1474 |
} |
|
1475 |
} |
|
1476 |
} |
|
1477 |
else { |
|
1478 |
detach(); |
|
1479 |
stat = false; |
|
1480 |
} |
|
1481 |
return stat; |
|
1482 |
} |
|
1483 |
||
1484 |
/** |
|
1485 |
* Responds to apparent emptiness in consume(). |
|
1486 |
*/ |
|
1487 |
private boolean checkEmpty(Flow.Subscriber<? super T> s, int c) { |
|
1488 |
boolean stat = true; |
|
1489 |
if (head == tail) { |
|
1490 |
if ((c & CONSUME) != 0) |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1491 |
CTL.compareAndSet(this, c, c & ~CONSUME); |
32989 | 1492 |
else if ((c & COMPLETE) != 0) { |
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1493 |
if (CTL.compareAndSet(this, c, DISABLED)) { |
32989 | 1494 |
try { |
1495 |
if (s != null) |
|
1496 |
s.onComplete(); |
|
1497 |
} catch (Throwable ignore) { |
|
1498 |
} |
|
1499 |
} |
|
1500 |
} |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1501 |
else if (CTL.compareAndSet(this, c, c & ~ACTIVE)) |
32989 | 1502 |
stat = false; |
1503 |
} |
|
1504 |
return stat; |
|
1505 |
} |
|
1506 |
||
1507 |
/** |
|
1508 |
* Responds to apparent zero demand in consume(). |
|
1509 |
*/ |
|
1510 |
private boolean checkDemand(int c) { |
|
1511 |
boolean stat = true; |
|
1512 |
if (demand == 0L) { |
|
1513 |
if ((c & CONSUME) != 0) |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1514 |
CTL.compareAndSet(this, c, c & ~CONSUME); |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1515 |
else if (CTL.compareAndSet(this, c, c & ~ACTIVE)) |
32989 | 1516 |
stat = false; |
1517 |
} |
|
1518 |
return stat; |
|
1519 |
} |
|
1520 |
||
1521 |
/** |
|
1522 |
* Processes exception in Subscriber.onNext. |
|
1523 |
*/ |
|
1524 |
private void handleOnNext(Flow.Subscriber<? super T> s, Throwable ex) { |
|
1525 |
BiConsumer<? super Flow.Subscriber<? super T>, ? super Throwable> h; |
|
1526 |
if ((h = onNextHandler) != null) { |
|
1527 |
try { |
|
1528 |
h.accept(s, ex); |
|
1529 |
} catch (Throwable ignore) { |
|
1530 |
} |
|
1531 |
} |
|
1532 |
onError(ex); |
|
1533 |
} |
|
1534 |
||
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1535 |
// VarHandle mechanics |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1536 |
private static final VarHandle CTL; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1537 |
private static final VarHandle TAIL; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1538 |
private static final VarHandle HEAD; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1539 |
private static final VarHandle DEMAND; |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1540 |
private static final VarHandle QA; |
32989 | 1541 |
|
1542 |
static { |
|
1543 |
try { |
|
39723
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1544 |
MethodHandles.Lookup l = MethodHandles.lookup(); |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1545 |
CTL = l.findVarHandle(BufferedSubscription.class, "ctl", |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1546 |
int.class); |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1547 |
TAIL = l.findVarHandle(BufferedSubscription.class, "tail", |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1548 |
int.class); |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1549 |
HEAD = l.findVarHandle(BufferedSubscription.class, "head", |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1550 |
int.class); |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1551 |
DEMAND = l.findVarHandle(BufferedSubscription.class, "demand", |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1552 |
long.class); |
9aa34e4a0469
8157523: Various improvements to ForkJoin/SubmissionPublisher code
dl
parents:
36936
diff
changeset
|
1553 |
QA = MethodHandles.arrayElementVarHandle(Object[].class); |
32989 | 1554 |
} catch (ReflectiveOperationException e) { |
1555 |
throw new Error(e); |
|
1556 |
} |
|
1557 |
||
1558 |
// Reduce the risk of rare disastrous classloading in first call to |
|
1559 |
// LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773 |
|
1560 |
Class<?> ensureLoaded = LockSupport.class; |
|
1561 |
} |
|
1562 |
} |
|
1563 |
} |