Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowablePublish.java

raw
1 /*
2 * Copyright (c) 2016-present, RxJava Contributors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
11 * the License for the specific language governing permissions and limitations under the License.
12 */
13
14 package io.reactivex.rxjava3.internal.operators.flowable;
15
16 import java.util.concurrent.atomic.*;
17
18 import org.reactivestreams.*;
19
20 import io.reactivex.rxjava3.core.FlowableSubscriber;
21 import io.reactivex.rxjava3.disposables.Disposable;
22 import io.reactivex.rxjava3.exceptions.*;
23 import io.reactivex.rxjava3.flowables.ConnectableFlowable;
24 import io.reactivex.rxjava3.functions.Consumer;
25 import io.reactivex.rxjava3.internal.fuseable.*;
26 import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
27 import io.reactivex.rxjava3.internal.util.*;
28 import io.reactivex.rxjava3.operators.QueueSubscription;
29 import io.reactivex.rxjava3.operators.SimpleQueue;
30 import io.reactivex.rxjava3.operators.SpscArrayQueue;
31 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
32
33 /**
34 * Shares a single underlying connection to the upstream Publisher
35 * and multicasts events to all subscribed subscribers until the upstream
36 * completes or the connection is disposed.
37 * <p>
38 * The difference to FlowablePublish is that when the upstream terminates,
39 * late subscribers will receive that terminal event until the connection is
40 * disposed and the ConnectableFlowable is reset to its fresh state.
41 *
42 * @param <T> the element type
43 * @since 2.2.10
44 */
45 public final class FlowablePublish<T> extends ConnectableFlowable<T>
46 implements HasUpstreamPublisher<T> {
47
48 final Publisher<T> source;
49
50 final int bufferSize;
51
52 final AtomicReference<PublishConnection<T>> current;
53
54 public FlowablePublish(Publisher<T> source, int bufferSize) {
55 this.source = source;
56 this.bufferSize = bufferSize;
57 this.current = new AtomicReference<>();
58 }
59
60 @Override
61 public Publisher<T> source() {
62 return source;
63 }
64
65 @Override
66 public void connect(Consumer<? super Disposable> connection) {
67 PublishConnection<T> conn;
68 boolean doConnect = false;
69
70 for (;;) {
71 conn = current.get();
72
73 if (conn == null || conn.isDisposed()) {
74 PublishConnection<T> fresh = new PublishConnection<>(current, bufferSize);
75 if (!current.compareAndSet(conn, fresh)) {
76 continue;
77 }
78 conn = fresh;
79 }
80
81 doConnect = !conn.connect.get() && conn.connect.compareAndSet(false, true);
82 break;
83 }
84
85 try {
86 connection.accept(conn);
87 } catch (Throwable ex) {
88 Exceptions.throwIfFatal(ex);
89 throw ExceptionHelper.wrapOrThrow(ex);
90 }
91
92 if (doConnect) {
93 source.subscribe(conn);
94 }
95 }
96
97 @Override
98 protected void subscribeActual(Subscriber<? super T> s) {
99 PublishConnection<T> conn;
100
101 for (;;) {
102 conn = current.get();
103
104 // don't create a fresh connection if the current is disposed
105 if (conn == null) {
106 PublishConnection<T> fresh = new PublishConnection<>(current, bufferSize);
107 if (!current.compareAndSet(conn, fresh)) {
108 continue;
109 }
110 conn = fresh;
111 }
112
113 break;
114 }
115
116 InnerSubscription<T> inner = new InnerSubscription<>(s, conn);
117 s.onSubscribe(inner);
118
119 if (conn.add(inner)) {
120 if (inner.isCancelled()) {
121 conn.remove(inner);
122 } else {
123 conn.drain();
124 }
125 return;
126 }
127
128 Throwable ex = conn.error;
129 if (ex != null) {
130 inner.downstream.onError(ex);
131 } else {
132 inner.downstream.onComplete();
133 }
134 }
135
136 @Override
137 public void reset() {
138 PublishConnection<T> conn = current.get();
139 if (conn != null && conn.isDisposed()) {
140 current.compareAndSet(conn, null);
141 }
142 }
143
144 static final class PublishConnection<T>
145 extends AtomicInteger
146 implements FlowableSubscriber<T>, Disposable {
147
148 private static final long serialVersionUID = -1672047311619175801L;
149
150 final AtomicReference<PublishConnection<T>> current;
151
152 final AtomicReference<Subscription> upstream;
153
154 final AtomicBoolean connect;
155
156 final AtomicReference<InnerSubscription<T>[]> subscribers;
157
158 final int bufferSize;
159
160 volatile SimpleQueue<T> queue;
161
162 int sourceMode;
163
164 volatile boolean done;
165 Throwable error;
166
167 int consumed;
168
169 @SuppressWarnings("rawtypes")
170 static final InnerSubscription[] EMPTY = new InnerSubscription[0];
171 @SuppressWarnings("rawtypes")
172 static final InnerSubscription[] TERMINATED = new InnerSubscription[0];
173
174 @SuppressWarnings("unchecked")
175 PublishConnection(AtomicReference<PublishConnection<T>> current, int bufferSize) {
176 this.current = current;
177 this.upstream = new AtomicReference<>();
178 this.connect = new AtomicBoolean();
179 this.bufferSize = bufferSize;
180 this.subscribers = new AtomicReference<>(EMPTY);
181 }
182
183 @SuppressWarnings("unchecked")
184 @Override
185 public void dispose() {
186 subscribers.getAndSet(TERMINATED);
187 current.compareAndSet(this, null);
188 SubscriptionHelper.cancel(upstream);
189 }
190
191 @Override
192 public boolean isDisposed() {
193 return subscribers.get() == TERMINATED;
194 }
195
196 @Override
197 public void onSubscribe(Subscription s) {
198 if (SubscriptionHelper.setOnce(this.upstream, s)) {
199 if (s instanceof QueueSubscription) {
200 @SuppressWarnings("unchecked")
201 QueueSubscription<T> qs = (QueueSubscription<T>) s;
202
203 int m = qs.requestFusion(QueueSubscription.ANY | QueueSubscription.BOUNDARY);
204 if (m == QueueSubscription.SYNC) {
205 sourceMode = m;
206 queue = qs;
207 done = true;
208 drain();
209 return;
210 }
211 if (m == QueueSubscription.ASYNC) {
212 sourceMode = m;
213 queue = qs;
214 s.request(bufferSize);
215 return;
216 }
217 }
218
219 queue = new SpscArrayQueue<>(bufferSize);
220
221 s.request(bufferSize);
222 }
223 }
224
225 @Override
226 public void onNext(T t) {
227 // we expect upstream to honor backpressure requests
228 if (sourceMode == QueueSubscription.NONE && !queue.offer(t)) {
229 onError(new MissingBackpressureException("Prefetch queue is full?!"));
230 return;
231 }
232 // since many things can happen concurrently, we have a common dispatch
233 // loop to act on the current state serially
234 drain();
235 }
236
237 @Override
238 public void onError(Throwable t) {
239 if (done) {
240 RxJavaPlugins.onError(t);
241 } else {
242 error = t;
243 done = true;
244 drain();
245 }
246 }
247
248 @Override
249 public void onComplete() {
250 done = true;
251 drain();
252 }
253
254 void drain() {
255 if (getAndIncrement() != 0) {
256 return;
257 }
258
259 int missed = 1;
260 SimpleQueue<T> queue = this.queue;
261 int consumed = this.consumed;
262 int limit = this.bufferSize - (this.bufferSize >> 2);
263 boolean async = this.sourceMode != QueueSubscription.SYNC;
264
265 outer:
266 for (;;) {
267 if (queue != null) {
268 long minDemand = Long.MAX_VALUE;
269 boolean hasDemand = false;
270
271 InnerSubscription<T>[] consumers = subscribers.get();
272
273 for (InnerSubscription<T> inner : consumers) {
274 long request = inner.get();
275 if (request != Long.MIN_VALUE) {
276 hasDemand = true;
277 minDemand = Math.min(request - inner.emitted, minDemand);
278 }
279 }
280
281 if (!hasDemand) {
282 minDemand = 0L;
283 }
284
285 while (minDemand != 0L) {
286 boolean d = done;
287 T v;
288
289 try {
290 v = queue.poll();
291 } catch (Throwable ex) {
292 Exceptions.throwIfFatal(ex);
293 upstream.get().cancel();
294 queue.clear();
295 done = true;
296 signalError(ex);
297 return;
298 }
299
300 boolean empty = v == null;
301
302 if (checkTerminated(d, empty)) {
303 return;
304 }
305
306 if (empty) {
307 break;
308 }
309
310 for (InnerSubscription<T> inner : consumers) {
311 if (!inner.isCancelled()) {
312 inner.downstream.onNext(v);
313 inner.emitted++;
314 }
315 }
316
317 if (async && ++consumed == limit) {
318 consumed = 0;
319 upstream.get().request(limit);
320 }
321 minDemand--;
322
323 if (consumers != subscribers.get()) {
324 continue outer;
325 }
326 }
327
328 if (checkTerminated(done, queue.isEmpty())) {
329 return;
330 }
331 }
332
333 this.consumed = consumed;
334 missed = addAndGet(-missed);
335 if (missed == 0) {
336 break;
337 }
338 if (queue == null) {
339 queue = this.queue;
340 }
341 }
342 }
343
344 @SuppressWarnings("unchecked")
345 boolean checkTerminated(boolean isDone, boolean isEmpty) {
346 if (isDone && isEmpty) {
347 Throwable ex = error;
348
349 if (ex != null) {
350 signalError(ex);
351 } else {
352 for (InnerSubscription<T> inner : subscribers.getAndSet(TERMINATED)) {
353 if (!inner.isCancelled()) {
354 inner.downstream.onComplete();
355 }
356 }
357 }
358 return true;
359 }
360 return false;
361 }
362
363 @SuppressWarnings("unchecked")
364 void signalError(Throwable ex) {
365 for (InnerSubscription<T> inner : subscribers.getAndSet(TERMINATED)) {
366 if (!inner.isCancelled()) {
367 inner.downstream.onError(ex);
368 }
369 }
370 }
371
372 boolean add(InnerSubscription<T> inner) {
373 // the state can change so we do a CAS loop to achieve atomicity
374 for (;;) {
375 // get the current producer array
376 InnerSubscription<T>[] c = subscribers.get();
377 // if this subscriber-to-source reached a terminal state by receiving
378 // an onError or onComplete, just refuse to add the new producer
379 if (c == TERMINATED) {
380 return false;
381 }
382 // we perform a copy-on-write logic
383 int len = c.length;
384 @SuppressWarnings("unchecked")
385 InnerSubscription<T>[] u = new InnerSubscription[len + 1];
386 System.arraycopy(c, 0, u, 0, len);
387 u[len] = inner;
388 // try setting the subscribers array
389 if (subscribers.compareAndSet(c, u)) {
390 return true;
391 }
392 // if failed, some other operation succeeded (another add, remove or termination)
393 // so retry
394 }
395 }
396
397 @SuppressWarnings("unchecked")
398 void remove(InnerSubscription<T> inner) {
399 // the state can change so we do a CAS loop to achieve atomicity
400 for (;;) {
401 // let's read the current subscribers array
402 InnerSubscription<T>[] c = subscribers.get();
403 int len = c.length;
404 // if it is either empty or terminated, there is nothing to remove so we quit
405 if (len == 0) {
406 break;
407 }
408 // let's find the supplied producer in the array
409 // although this is O(n), we don't expect too many child subscribers in general
410 int j = -1;
411 for (int i = 0; i < len; i++) {
412 if (c[i] == inner) {
413 j = i;
414 break;
415 }
416 }
417 // we didn't find it so just quit
418 if (j < 0) {
419 return;
420 }
421 // we do copy-on-write logic here
422 InnerSubscription<T>[] u;
423 // we don't create a new empty array if producer was the single inhabitant
424 // but rather reuse an empty array
425 if (len == 1) {
426 u = EMPTY;
427 } else {
428 // otherwise, create a new array one less in size
429 u = new InnerSubscription[len - 1];
430 // copy elements being before the given producer
431 System.arraycopy(c, 0, u, 0, j);
432 // copy elements being after the given producer
433 System.arraycopy(c, j + 1, u, j, len - j - 1);
434 }
435 // try setting this new array as
436 if (subscribers.compareAndSet(c, u)) {
437 break;
438 }
439 // if we failed, it means something else happened
440 // (a concurrent add/remove or termination), we need to retry
441 }
442 }
443 }
444
445 static final class InnerSubscription<T> extends AtomicLong
446 implements Subscription {
447
448 private static final long serialVersionUID = 2845000326761540265L;
449
450 final Subscriber<? super T> downstream;
451
452 final PublishConnection<T> parent;
453
454 long emitted;
455
456 InnerSubscription(Subscriber<? super T> downstream, PublishConnection<T> parent) {
457 this.downstream = downstream;
458 this.parent = parent;
459 }
460
461 @Override
462 public void request(long n) {
463 if (SubscriptionHelper.validate(n)) {
464 BackpressureHelper.addCancel(this, n);
465 parent.drain();
466 }
467 }
468
469 @Override
470 public void cancel() {
471 if (getAndSet(Long.MIN_VALUE) != Long.MIN_VALUE) {
472 parent.remove(this);
473 parent.drain();
474 }
475 }
476
477 public boolean isCancelled() {
478 return get() == Long.MIN_VALUE;
479 }
480 }
481 }