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