-
Notifications
You must be signed in to change notification settings - Fork 180
/
SpScPublisherProcessor.java
297 lines (275 loc) · 13.7 KB
/
SpScPublisherProcessor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*
* Copyright © 2019 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.concurrent.api.internal;
import io.servicetalk.concurrent.PublisherSource;
import io.servicetalk.concurrent.api.Publisher;
import io.servicetalk.concurrent.internal.DuplicateSubscribeException;
import io.servicetalk.concurrent.internal.FlowControlUtils;
import io.servicetalk.concurrent.internal.QueueFullException;
import io.servicetalk.concurrent.internal.TerminalNotification;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import javax.annotation.Nullable;
import static io.servicetalk.concurrent.internal.SubscriberUtils.deliverTerminalFromSource;
import static io.servicetalk.concurrent.internal.SubscriberUtils.isRequestNValid;
import static io.servicetalk.concurrent.internal.SubscriberUtils.newExceptionForInvalidRequestN;
import static io.servicetalk.utils.internal.PlatformDependent.newUnboundedSpscQueue;
/**
* A {@link Publisher} that allows for signals to be directly injected via {@link #sendOnNext(Object)},
* {@link #sendOnComplete()}, and {@link #sendOnError(Throwable)}. The threading restrictions for this class are:
* <ul>
* <li><strong>S</strong>ingle<strong>P</strong>roducer meaning only a single thread is allowed to interact with
* {@link #sendOnNext(Object)}, {@link #sendOnComplete()}, and {@link #sendOnError(Throwable)} methods.</li>
* <li><strong>S</strong>ingle<strong>C</strong>onsumer meaning only a single {@link PublisherSource.Subscriber} is
* supported. Other operators can be used to add support for multiple {@link PublisherSource.Subscriber}s if necessary.
* </li>
* </ul>
*
* @param <T> The type of {@link Publisher}.
*/
public final class SpScPublisherProcessor<T> extends SubscribablePublisher<T> {
private static final AtomicLongFieldUpdater<SpScPublisherProcessor> requestedUpdater =
AtomicLongFieldUpdater.newUpdater(SpScPublisherProcessor.class, "requested");
private static final AtomicIntegerFieldUpdater<SpScPublisherProcessor> onNextQueueSizeUpdater =
AtomicIntegerFieldUpdater.newUpdater(SpScPublisherProcessor.class, "onNextQueueSize");
private static final AtomicReferenceFieldUpdater<SpScPublisherProcessor, Subscriber> subscriberUpdater =
AtomicReferenceFieldUpdater.newUpdater(SpScPublisherProcessor.class, Subscriber.class,
"subscriber");
private static final long CANCELLED = Long.MIN_VALUE;
private static final Object NULL_TOKEN = new Object();
private static final Subscriber<?> CALLING_ON_SUBSCRIBE = newErrorSubscriber();
private static final Subscriber<?> DRAINING_SUBSCRIBER = newErrorSubscriber();
private static final Subscriber<?> TERMINATING_SUBSCRIBER = newErrorSubscriber();
private static final Subscriber<?> TERMINATED_SUBSCRIBER = newErrorSubscriber();
@Nullable
private volatile Subscriber<? super T> subscriber;
private volatile int onNextQueueSize;
private volatile long requested;
private final Queue<Object> signalQueue;
private final int maxOnNextQueueSize;
/**
* Create a new instance.
*
* @param maxOnNextQueueSize The maximum amount of {@link PublisherSource.Subscriber#onNext(Object)} signals that
* can be queued from {@link #sendOnNext(Object)}.
*/
public SpScPublisherProcessor(int maxOnNextQueueSize) {
this(maxOnNextQueueSize, 2);
}
/**
* Create a new instance.
*
* @param maxOnNextQueueSize The maximum amount of {@link PublisherSource.Subscriber#onNext(Object)} signals that
* can be queued from {@link #sendOnNext(Object)}.
* @param initialQueueSize The initial size of the {@link Queue} to hold signals for the
* {@link #sendOnNext(Object)}, {@link #sendOnComplete()}, and {@link #sendOnError(Throwable)} methods.
*/
private SpScPublisherProcessor(int maxOnNextQueueSize, int initialQueueSize) {
if (maxOnNextQueueSize <= 0) {
throw new IllegalArgumentException("maxOnNextQueueSize: " + maxOnNextQueueSize + " (expected >0)");
}
this.maxOnNextQueueSize = maxOnNextQueueSize;
signalQueue = newUnboundedSpscQueue(initialQueueSize);
}
@Override
protected void handleSubscribe(final Subscriber<? super T> s) {
for (;;) {
final Subscriber<? super T> subscriber = this.subscriber;
if (subscriber != null) {
deliverTerminalFromSource(s, new DuplicateSubscribeException(subscriber, s));
return;
} else if (subscriberUpdater.compareAndSet(this, null, CALLING_ON_SUBSCRIBE)) {
s.onSubscribe(new Subscription() {
@Override
public void request(final long n) {
if (isRequestNValid(n)) {
if (requestedUpdater.getAndAccumulate(SpScPublisherProcessor.this, n,
FlowControlUtils::addWithOverflowProtectionIfNotNegative) == 0) {
drainQueue();
}
} else {
for (;;) {
final long requested = SpScPublisherProcessor.this.requested;
if (requested < 0) {
break;
} else if (requestedUpdater.compareAndSet(SpScPublisherProcessor.this,
requested, n == CANCELLED ? CANCELLED + 1 : n)) {
drainQueue();
break;
}
}
}
}
@Override
public void cancel() {
if (requestedUpdater.getAndSet(SpScPublisherProcessor.this, CANCELLED) !=
CANCELLED) {
drainQueue(); // just to clear the queue and make objects eligible for GC.
}
}
});
// We hold off all interactions with the Subscriber until control flow returns from onSubscribe to
// avoid concurrently invoking the Subscriber.
if (subscriberUpdater.compareAndSet(this, CALLING_ON_SUBSCRIBE, s)) {
drainQueue();
}
break;
}
}
}
/**
* Send an {@link PublisherSource.Subscriber#onNext(Object)} signal to the subscriber of this {@link Publisher}.
*
* @param t The signals for {@link PublisherSource.Subscriber#onNext(Object)}.
* @throws QueueFullException if the queue of signals would exceed the maximum size.
*/
public void sendOnNext(@Nullable final T t) {
// This is a single producer process, so we optimistically increment and may maxOnNextQueueSize, but we can
// decrement after the fact if this is the case to prevent overflow on subsequent calls.
if (onNextQueueSizeUpdater.getAndIncrement(this) == maxOnNextQueueSize) {
onNextQueueSizeUpdater.decrementAndGet(this);
final QueueFullException e = new QueueFullException("signalQueue", maxOnNextQueueSize);
signalQueue.add(TerminalNotification.error(e));
drainQueue();
// The calling thread should be notified that the queue is full, and if this is in the context of another
// asynchronous source it will serve as a best effort to terminate that source.
throw e;
} else {
signalQueue.add(t == null ? NULL_TOKEN : t);
drainQueue();
}
}
/**
* Send an {@link PublisherSource.Subscriber#onError(Throwable)} signal to the subscriber of this {@link Publisher}.
*
* @param t The signals for {@link PublisherSource.Subscriber#onError(Throwable)}.
*/
public void sendOnError(final Throwable t) {
signalQueue.add(TerminalNotification.error(t));
drainQueue();
}
/**
* Send an {@link PublisherSource.Subscriber#onComplete()} signal to the subscriber of this {@link Publisher}.
*/
public void sendOnComplete() {
signalQueue.add(TerminalNotification.complete());
drainQueue();
}
private void drainQueue() {
for (;;) {
final Subscriber<? super T> subscriber = this.subscriber;
if (subscriber == null || subscriber == CALLING_ON_SUBSCRIBE || subscriber == DRAINING_SUBSCRIBER) {
if (subscriberUpdater.compareAndSet(this, subscriber, subscriber)) {
break;
}
} else if (subscriber == TERMINATING_SUBSCRIBER) {
// forcing the state to TERMINATED_SUBSCRIBER either signals to the consumer thread that it needs to
// drain again, or we will take ownership of the consumer and drain if already terminated.
if (subscriberUpdater.getAndSet(this, TERMINATED_SUBSCRIBER) == TERMINATED_SUBSCRIBER) {
signalQueue.clear();
}
break;
} else if (subscriber == TERMINATED_SUBSCRIBER) {
signalQueue.clear();
break;
} else {
for (;;) {
if (!subscriberUpdater.compareAndSet(this, subscriber, DRAINING_SUBSCRIBER)) {
return;
}
Object signal;
long previousRequested;
// getAndAccumulate because we want to know if before the decrement, the value was positive.
while ((previousRequested = requestedUpdater.getAndAccumulate(this, 1,
FlowControlUtils::subtractIfPositive)) > 0) {
signal = signalQueue.poll();
if (signal == null) {
previousRequested = requestedUpdater.accumulateAndGet(this, 1,
FlowControlUtils::addWithOverflowProtectionIfNotNegative);
break;
} else if (signal instanceof TerminalNotification) {
clearQueueAndTerminate();
((TerminalNotification) signal).terminate(subscriber);
return;
} else {
try {
onNextQueueSizeUpdater.decrementAndGet(this);
@SuppressWarnings("unchecked")
final T tSignal = signal == NULL_TOKEN ? null : (T) signal;
subscriber.onNext(tSignal);
} catch (Throwable cause) {
clearQueueAndTerminate();
subscriber.onError(cause);
return;
}
}
}
if (previousRequested < 0) {
clearQueueAndTerminate();
if (previousRequested != CANCELLED) {
subscriber.onError(newExceptionForInvalidRequestN(previousRequested));
}
return;
} else if ((signal = signalQueue.peek()) instanceof TerminalNotification) {
clearQueueAndTerminate();
((TerminalNotification) signal).terminate(subscriber);
return;
}
// "unlock" the subscriber.
this.subscriber = subscriber;
final boolean empty = signalQueue.isEmpty();
previousRequested = requested;
if (!empty && previousRequested == 0 || empty && previousRequested >= 0) {
break;
}
}
break;
}
}
}
private void clearQueueAndTerminate() {
do {
subscriber = terminatingSubscriber();
signalQueue.clear();
} while (!subscriberUpdater.compareAndSet(this, TERMINATING_SUBSCRIBER, TERMINATED_SUBSCRIBER));
}
private static <T> Subscriber<T> newErrorSubscriber() {
return new Subscriber<T>() {
@Override
public void onSubscribe(final Subscription subscription) {
throw new UnsupportedOperationException();
}
@Override
public void onNext(@Nullable final T o) {
throw new UnsupportedOperationException();
}
@Override
public void onError(final Throwable t) {
throw new UnsupportedOperationException();
}
@Override
public void onComplete() {
throw new UnsupportedOperationException();
}
};
}
@SuppressWarnings("unchecked")
private static <T> Subscriber<T> terminatingSubscriber() {
return (Subscriber<T>) TERMINATING_SUBSCRIBER;
}
}