use of co.paralleluniverse.strands.channels.ReceivePort in project quasar by puniverse.
the class TwoSidedTest method twoSidedTestWithProcessor.
@Test
public void twoSidedTestWithProcessor() throws Exception {
// Publisher
final Channel<Integer> publisherChannel = Channels.newChannel(random() ? 0 : 5, OverflowPolicy.BLOCK);
final Strand publisherStrand = new Fiber<Void>(new SuspendableRunnable() {
@Override
public void run() throws SuspendExecution, InterruptedException {
for (long i = 0; i < ELEMENTS; i++) publisherChannel.send((int) (i % 1000));
publisherChannel.close();
}
}).start();
final Publisher<Integer> publisher = ReactiveStreams.toPublisher(publisherChannel);
// Processor
final Processor<Integer, Integer> processor = ReactiveStreams.toProcessor(5, OverflowPolicy.BLOCK, new SuspendableAction2<ReceivePort<Integer>, SendPort<Integer>>() {
@Override
public void call(ReceivePort<Integer> in, SendPort<Integer> out) throws SuspendExecution, InterruptedException {
long count = 0;
for (Integer element; ((element = in.receive()) != null); count++) {
out.send(element * 10);
out.send(element * 100);
// Fiber.sleep(1); // just for fun
assertTrue(count < ELEMENTS);
}
assertEquals(ELEMENTS, count);
out.close();
}
});
publisher.subscribe(processor);
// Subscriber
final ReceivePort<Integer> subscriberChannel = ReactiveStreams.subscribe(buffer, overflowPolicy, processor);
final Strand subscriberStrand = new Fiber<Void>(new SuspendableRunnable() {
@Override
public void run() throws SuspendExecution, InterruptedException {
long count = 0;
for (; ; ) {
Integer x = subscriberChannel.receive();
if (x == null)
break;
assertTrue(x % 10 == 0);
if (count % 2 != 0)
assertTrue(x % 100 == 0);
count++;
}
subscriberChannel.close();
assertEquals(ELEMENTS * 2, count);
}
}).start();
subscriberStrand.join(5, TimeUnit.SECONDS);
publisherStrand.join(5, TimeUnit.SECONDS);
}
Aggregations