|
| 1 | +package org.reactivestreams.example.multicast; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.HashSet; |
| 5 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 6 | +import java.util.concurrent.atomic.AtomicLong; |
| 7 | + |
| 8 | +/** |
| 9 | + * Simulate a network connection that is firing data at you. |
| 10 | + * <p> |
| 11 | + * Purposefully not using the `Subscriber` and `Publisher` types to not confuse things with `StockPricePublisher` |
| 12 | + */ |
| 13 | +public class NeverEndingStockStream { |
| 14 | + |
| 15 | + private static final NeverEndingStockStream INSTANCE = new NeverEndingStockStream(); |
| 16 | + |
| 17 | + private NeverEndingStockStream() { |
| 18 | + } |
| 19 | + |
| 20 | + // using array because it is far faster than list/set for iteration |
| 21 | + // which is where most of the time in the tight loop will go (... well, beside object allocation) |
| 22 | + private volatile Handler[] handlers = new Handler[0]; |
| 23 | + |
| 24 | + public static synchronized void addHandler(Handler handler) { |
| 25 | + if (INSTANCE.handlers.length == 0) { |
| 26 | + INSTANCE.handlers = new Handler[] { handler }; |
| 27 | + } else { |
| 28 | + Handler[] newHandlers = new Handler[INSTANCE.handlers.length + 1]; |
| 29 | + System.arraycopy(INSTANCE.handlers, 0, newHandlers, 0, INSTANCE.handlers.length); |
| 30 | + newHandlers[newHandlers.length - 1] = handler; |
| 31 | + INSTANCE.handlers = newHandlers; |
| 32 | + } |
| 33 | + INSTANCE.startIfNeeded(); |
| 34 | + } |
| 35 | + |
| 36 | + public static synchronized void removeHandler(Handler handler) { |
| 37 | + // too lazy to do the array handling |
| 38 | + HashSet<Handler> set = new HashSet<>(Arrays.asList(INSTANCE.handlers)); |
| 39 | + set.remove(handler); |
| 40 | + INSTANCE.handlers = set.toArray(new Handler[set.size()]); |
| 41 | + } |
| 42 | + |
| 43 | + public static interface Handler { |
| 44 | + public void handle(Stock event); |
| 45 | + } |
| 46 | + |
| 47 | + private final AtomicBoolean running = new AtomicBoolean(false); |
| 48 | + private final AtomicLong stockIndex = new AtomicLong(); |
| 49 | + |
| 50 | + private void startIfNeeded() { |
| 51 | + if (running.compareAndSet(false, true)) { |
| 52 | + new Thread(new Runnable() { |
| 53 | + |
| 54 | + @Override |
| 55 | + public void run() { |
| 56 | + while (handlers.length > 0) { |
| 57 | + long l = stockIndex.incrementAndGet(); |
| 58 | + Stock s = new Stock(l); |
| 59 | + for (Handler h : handlers) { |
| 60 | + h.handle(s); |
| 61 | + } |
| 62 | + try { |
| 63 | + // just so it is someone sane how fast this is moving |
| 64 | + Thread.sleep(1); |
| 65 | + } catch (InterruptedException e) { |
| 66 | + } |
| 67 | + } |
| 68 | + running.set(false); |
| 69 | + } |
| 70 | + |
| 71 | + }).start(); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | +} |
0 commit comments