001/*************************************************** 002 * Licensed under MIT No Attribution (SPDX: MIT-0) * 003 ***************************************************/ 004 005package org.reactivestreams.example.unicast; 006 007import org.reactivestreams.Publisher; 008import org.reactivestreams.Subscriber; 009import org.reactivestreams.Subscription; 010 011import java.util.Iterator; 012import java.util.Collections; 013import java.util.concurrent.Executor; 014import java.util.concurrent.atomic.AtomicBoolean; 015import java.util.concurrent.ConcurrentLinkedQueue; 016 017/** 018 * AsyncIterablePublisher is an implementation of Reactive Streams `Publisher` 019 * which executes asynchronously, using a provided `Executor` and produces elements 020 * from a given `Iterable` in a "unicast" configuration to its `Subscribers`. 021 * 022 * NOTE: The code below uses a lot of try-catches to show the reader where exceptions can be expected, and where they are forbidden. 023 */ 024public class AsyncIterablePublisher<T> implements Publisher<T> { 025 private final static int DEFAULT_BATCHSIZE = 1024; 026 027 private final Iterable<T> elements; // This is our data source / generator 028 private final Executor executor; // This is our thread pool, which will make sure that our Publisher runs asynchronously to its Subscribers 029 private final int batchSize; // In general, if one uses an `Executor`, one should be nice nad not hog a thread for too long, this is the cap for that, in elements 030 031 public AsyncIterablePublisher(final Iterable<T> elements, final Executor executor) { 032 this(elements, DEFAULT_BATCHSIZE, executor); 033 } 034 035 public AsyncIterablePublisher(final Iterable<T> elements, final int batchSize, final Executor executor) { 036 if (elements == null) throw null; 037 if (executor == null) throw null; 038 if (batchSize < 1) throw new IllegalArgumentException("batchSize must be greater than zero!"); 039 this.elements = elements; 040 this.executor = executor; 041 this.batchSize = batchSize; 042 } 043 044 @Override 045 public void subscribe(final Subscriber<? super T> s) { 046 // As per rule 1.11, we have decided to support multiple subscribers in a unicast configuration 047 // for this `Publisher` implementation. 048 // As per 2.13, this method must return normally (i.e. not throw) 049 new SubscriptionImpl(s).init(); 050 } 051 052 // These represent the protocol of the `AsyncIterablePublishers` SubscriptionImpls 053 static interface Signal {}; 054 enum Cancel implements Signal { Instance; }; 055 enum Subscribe implements Signal { Instance; }; 056 enum Send implements Signal { Instance; }; 057 static final class Request implements Signal { 058 final long n; 059 Request(final long n) { 060 this.n = n; 061 } 062 }; 063 064 // This is our implementation of the Reactive Streams `Subscription`, 065 // which represents the association between a `Publisher` and a `Subscriber`. 066 final class SubscriptionImpl implements Subscription, Runnable { 067 final Subscriber<? super T> subscriber; // We need a reference to the `Subscriber` so we can talk to it 068 private boolean cancelled = false; // This flag will track whether this `Subscription` is to be considered cancelled or not 069 private long demand = 0; // Here we track the current demand, i.e. what has been requested but not yet delivered 070 private Iterator<T> iterator; // This is our cursor into the data stream, which we will send to the `Subscriber` 071 072 SubscriptionImpl(final Subscriber<? super T> subscriber) { 073 // As per rule 1.09, we need to throw a `java.lang.NullPointerException` if the `Subscriber` is `null` 074 if (subscriber == null) throw null; 075 this.subscriber = subscriber; 076 } 077 078 // This `ConcurrentLinkedQueue` will track signals that are sent to this `Subscription`, like `request` and `cancel` 079 private final ConcurrentLinkedQueue<Signal> inboundSignals = new ConcurrentLinkedQueue<Signal>(); 080 081 // We are using this `AtomicBoolean` to make sure that this `Subscription` doesn't run concurrently with itself, 082 // which would violate rule 1.3 among others (no concurrent notifications). 083 private final AtomicBoolean on = new AtomicBoolean(false); 084 085 // This method will register inbound demand from our `Subscriber` and validate it against rule 3.9 and rule 3.17 086 private void doRequest(final long n) { 087 if (n < 1) 088 terminateDueTo(new IllegalArgumentException(subscriber + " violated the Reactive Streams rule 3.9 by requesting a non-positive number of elements.")); 089 else if (demand + n < 1) { 090 // As governed by rule 3.17, when demand overflows `Long.MAX_VALUE` we treat the signalled demand as "effectively unbounded" 091 demand = Long.MAX_VALUE; // Here we protect from the overflow and treat it as "effectively unbounded" 092 doSend(); // Then we proceed with sending data downstream 093 } else { 094 demand += n; // Here we record the downstream demand 095 doSend(); // Then we can proceed with sending data downstream 096 } 097 } 098 099 // This handles cancellation requests, and is idempotent, thread-safe and not synchronously performing heavy computations as specified in rule 3.5 100 private void doCancel() { 101 cancelled = true; 102 } 103 104 // Instead of executing `subscriber.onSubscribe` synchronously from within `Publisher.subscribe` 105 // we execute it asynchronously, this is to avoid executing the user code (`Iterable.iterator`) on the calling thread. 106 // It also makes it easier to follow rule 1.9 107 private void doSubscribe() { 108 try { 109 iterator = elements.iterator(); 110 if (iterator == null) 111 iterator = Collections.<T>emptyList().iterator(); // So we can assume that `iterator` is never null 112 } catch(final Throwable t) { 113 subscriber.onSubscribe(new Subscription() { // We need to make sure we signal onSubscribe before onError, obeying rule 1.9 114 @Override public void cancel() {} 115 @Override public void request(long n) {} 116 }); 117 terminateDueTo(t); // Here we send onError, obeying rule 1.09 118 } 119 120 if (!cancelled) { 121 // Deal with setting up the subscription with the subscriber 122 try { 123 subscriber.onSubscribe(this); 124 } catch(final Throwable t) { // Due diligence to obey 2.13 125 terminateDueTo(new IllegalStateException(subscriber + " violated the Reactive Streams rule 2.13 by throwing an exception from onSubscribe.", t)); 126 } 127 128 // Deal with already complete iterators promptly 129 boolean hasElements = false; 130 try { 131 hasElements = iterator.hasNext(); 132 } catch(final Throwable t) { 133 terminateDueTo(t); // If hasNext throws, there's something wrong and we need to signal onError as per 1.2, 1.4, 134 } 135 136 // If we don't have anything to deliver, we're already done, so lets do the right thing and 137 // not wait for demand to deliver `onComplete` as per rule 1.2 and 1.3 138 if (!hasElements) { 139 try { 140 doCancel(); // Rule 1.6 says we need to consider the `Subscription` cancelled when `onComplete` is signalled 141 subscriber.onComplete(); 142 } catch(final Throwable t) { // As per rule 2.13, `onComplete` is not allowed to throw exceptions, so we do what we can, and log this. 143 (new IllegalStateException(subscriber + " violated the Reactive Streams rule 2.13 by throwing an exception from onComplete.", t)).printStackTrace(System.err); 144 } 145 } 146 } 147 } 148 149 // This is our behavior for producing elements downstream 150 private void doSend() { 151 try { 152 // In order to play nice with the `Executor` we will only send at-most `batchSize` before 153 // rescheduing ourselves and relinquishing the current thread. 154 int leftInBatch = batchSize; 155 do { 156 T next; 157 boolean hasNext; 158 try { 159 next = iterator.next(); // We have already checked `hasNext` when subscribing, so we can fall back to testing -after- `next` is called. 160 hasNext = iterator.hasNext(); // Need to keep track of End-of-Stream 161 } catch (final Throwable t) { 162 terminateDueTo(t); // If `next` or `hasNext` throws (they can, since it is user-provided), we need to treat the stream as errored as per rule 1.4 163 return; 164 } 165 subscriber.onNext(next); // Then we signal the next element downstream to the `Subscriber` 166 if (!hasNext) { // If we are at End-of-Stream 167 doCancel(); // We need to consider this `Subscription` as cancelled as per rule 1.6 168 subscriber.onComplete(); // Then we signal `onComplete` as per rule 1.2 and 1.5 169 } 170 } while (!cancelled // This makes sure that rule 1.8 is upheld, i.e. we need to stop signalling "eventually" 171 && --leftInBatch > 0 // This makes sure that we only send `batchSize` number of elements in one go (so we can yield to other Runnables) 172 && --demand > 0); // This makes sure that rule 1.1 is upheld (sending more than was demanded) 173 174 if (!cancelled && demand > 0) // If the `Subscription` is still alive and well, and we have demand to satisfy, we signal ourselves to send more data 175 signal(Send.Instance); 176 } catch(final Throwable t) { 177 // We can only get here if `onNext` or `onComplete` threw, and they are not allowed to according to 2.13, so we can only cancel and log here. 178 doCancel(); // Make sure that we are cancelled, since we cannot do anything else since the `Subscriber` is faulty. 179 (new IllegalStateException(subscriber + " violated the Reactive Streams rule 2.13 by throwing an exception from onNext or onComplete.", t)).printStackTrace(System.err); 180 } 181 } 182 183 // This is a helper method to ensure that we always `cancel` when we signal `onError` as per rule 1.6 184 private void terminateDueTo(final Throwable t) { 185 cancelled = true; // When we signal onError, the subscription must be considered as cancelled, as per rule 1.6 186 try { 187 subscriber.onError(t); // Then we signal the error downstream, to the `Subscriber` 188 } catch(final Throwable t2) { // If `onError` throws an exception, this is a spec violation according to rule 1.9, and all we can do is to log it. 189 (new IllegalStateException(subscriber + " violated the Reactive Streams rule 2.13 by throwing an exception from onError.", t2)).printStackTrace(System.err); 190 } 191 } 192 193 // What `signal` does is that it sends signals to the `Subscription` asynchronously 194 private void signal(final Signal signal) { 195 if (inboundSignals.offer(signal)) // No need to null-check here as ConcurrentLinkedQueue does this for us 196 tryScheduleToExecute(); // Then we try to schedule it for execution, if it isn't already 197 } 198 199 // This is the main "event loop" if you so will 200 @Override public final void run() { 201 if(on.get()) { // establishes a happens-before relationship with the end of the previous run 202 try { 203 final Signal s = inboundSignals.poll(); // We take a signal off the queue 204 if (!cancelled) { // to make sure that we follow rule 1.8, 3.6 and 3.7 205 206 // Below we simply unpack the `Signal`s and invoke the corresponding methods 207 if (s instanceof Request) 208 doRequest(((Request)s).n); 209 else if (s == Send.Instance) 210 doSend(); 211 else if (s == Cancel.Instance) 212 doCancel(); 213 else if (s == Subscribe.Instance) 214 doSubscribe(); 215 } 216 } finally { 217 on.set(false); // establishes a happens-before relationship with the beginning of the next run 218 if(!inboundSignals.isEmpty()) // If we still have signals to process 219 tryScheduleToExecute(); // Then we try to schedule ourselves to execute again 220 } 221 } 222 } 223 224 // This method makes sure that this `Subscription` is only running on one Thread at a time, 225 // this is important to make sure that we follow rule 1.3 226 private final void tryScheduleToExecute() { 227 if(on.compareAndSet(false, true)) { 228 try { 229 executor.execute(this); 230 } catch(Throwable t) { // If we can't run on the `Executor`, we need to fail gracefully 231 if (!cancelled) { 232 doCancel(); // First of all, this failure is not recoverable, so we need to follow rule 1.4 and 1.6 233 try { 234 terminateDueTo(new IllegalStateException("Publisher terminated due to unavailable Executor.", t)); 235 } finally { 236 inboundSignals.clear(); // We're not going to need these anymore 237 // This subscription is cancelled by now, but letting it become schedulable again means 238 // that we can drain the inboundSignals queue if anything arrives after clearing 239 on.set(false); 240 } 241 } 242 } 243 } 244 } 245 246 // Our implementation of `Subscription.request` sends a signal to the Subscription that more elements are in demand 247 @Override public void request(final long n) { 248 signal(new Request(n)); 249 } 250 // Our implementation of `Subscription.cancel` sends a signal to the Subscription that the `Subscriber` is not interested in any more elements 251 @Override public void cancel() { 252 signal(Cancel.Instance); 253 } 254 // The reason for the `init` method is that we want to ensure the `SubscriptionImpl` 255 // is completely constructed before it is exposed to the thread pool, therefor this 256 // method is only intended to be invoked once, and immediately after the constructor has 257 // finished. 258 void init() { 259 signal(Subscribe.Instance); 260 } 261 }; 262}