io.netty.util.concurrent.ImmediateEventExecutor Java Examples
The following examples show how to use
io.netty.util.concurrent.ImmediateEventExecutor.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DeferredStreamMessageTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void testStreaming() { final DeferredStreamMessage<String> m = new DeferredStreamMessage<>(); final DefaultStreamMessage<String> d = new DefaultStreamMessage<>(); m.delegate(d); final RecordingSubscriber subscriber = new RecordingSubscriber(); final List<String> recording = subscriber.recording; m.subscribe(subscriber, ImmediateEventExecutor.INSTANCE); assertThat(recording).containsExactly("onSubscribe"); d.write("A"); assertThat(recording).containsExactly("onSubscribe", "A"); d.close(); assertThat(recording).containsExactly("onSubscribe", "A", "onComplete"); assertThat(m.isOpen()).isFalse(); assertThat(m.isEmpty()).isFalse(); assertThat(m.whenComplete()).isCompletedWithValue(null); assertThat(d.isOpen()).isFalse(); assertThat(d.isEmpty()).isFalse(); assertThat(d.whenComplete()).isCompletedWithValue(null); }
Example #2
Source File: ClientLifecycleEventHandlerTest.java From hivemq-community-edition with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); executor1 = new PluginTaskExecutor(new AtomicLong()); executor1.postConstruct(); final EmbeddedChannel embeddedChannel = new EmbeddedChannel(); embeddedChannel.attr(ChannelAttributes.CLIENT_ID).set("test_client"); embeddedChannel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv5); when(channelHandlerContext.channel()).thenReturn(embeddedChannel); when(channelHandlerContext.executor()).thenReturn(ImmediateEventExecutor.INSTANCE); pluginTaskExecutorService = new PluginTaskExecutorServiceImpl(() -> executor1, mock(ShutdownHooks.class)); clientLifecycleEventHandler = new ClientLifecycleEventHandler(lifecycleEventListeners, pluginTaskExecutorService, hiveMQExtensions); }
Example #3
Source File: PluginInitializerHandlerTest.java From hivemq-community-edition with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); executor1 = new PluginTaskExecutor(new AtomicLong()); executor1.postConstruct(); embeddedChannel = new EmbeddedChannel(); embeddedChannel.attr(ChannelAttributes.CLIENT_ID).set("test_client"); embeddedChannel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv5); when(channelHandlerContext.channel()).thenReturn(embeddedChannel); when(channelHandlerContext.executor()).thenReturn(ImmediateEventExecutor.INSTANCE); pluginTaskExecutorService = new PluginTaskExecutorServiceImpl(() -> executor1, mock(ShutdownHooks.class)); pluginInitializerHandler = new PluginInitializerHandler(initializers, pluginTaskExecutorService, new ServerInformationImpl(new SystemInformationImpl(), listenerConfigurationService), hiveMQExtensions, clientSessionPersistence, mqttConnacker); }
Example #4
Source File: Pipe.java From netty-http2 with Apache License 2.0 | 6 votes |
/** * Receives a message from this pipe. * <p> * If the pipe is closed then this will return a failed future.</p> */ public Future<T> receive() { Node node; synchronized (this) { node = sendQueue.poll(); if (node == null) { if (closed) { return ImmediateEventExecutor.INSTANCE.newFailedFuture(PIPE_CLOSED); } Promise<T> promise = ImmediateEventExecutor.INSTANCE.newPromise(); receiveQueue.add(promise); return promise; } } node.promise.setSuccess(null); return ImmediateEventExecutor.INSTANCE.newSucceededFuture(node.message); }
Example #5
Source File: Pipe.java From netty-http2 with Apache License 2.0 | 6 votes |
/** * Sends a message to this pipe. Returns a {@link Future} that is completed * when the message is received. * <p> * If the pipe is closed then this will return a failed future.</p> * * @param message the message to send to the pipe * @return a {@link Future} that is satisfied when the message is received, * or a failed future if the pipe is closed. * @throws NullPointerException if the message is {@code null}. * @throws IllegalStateException if the message could not be added to the queue for some reason. * @see #receive() */ public Future<Void> send(T message) { Objects.requireNonNull(message, "msg"); Promise<T> receivePromise; synchronized (this) { if (closed) { return CLOSED_FUTURE; } receivePromise = receiveQueue.poll(); if (receivePromise == null) { Promise<Void> sendPromise = ImmediateEventExecutor.INSTANCE.newPromise(); sendQueue.add(new Node(message, sendPromise)); return sendPromise; } } receivePromise.setSuccess(message); return SENT_FUTURE; }
Example #6
Source File: RedissonTransferQueue.java From redisson with Apache License 2.0 | 6 votes |
public RFuture<V> pollAsync(long timeout, TimeUnit unit) { RPromise<V> result = new RedissonPromise<>(); result.setUncancellable(); TransferQueueServiceImpl s = new TransferQueueServiceImpl(); RFuture<Boolean> future = remoteService.tryExecuteAsync(TransferQueueService.class, s, ImmediateEventExecutor.INSTANCE, timeout, unit); future.onComplete((r, e) -> { if (e != null) { result.tryFailure(e); return; } result.trySuccess((V) s.getResult()); }); return result; }
Example #7
Source File: Http2ConnectionHandlerTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void canSendGoAwayUsingVoidPromise() throws Exception { handler = newHandler(); ByteBuf data = dummyData(); long errorCode = Http2Error.INTERNAL_ERROR.code(); handler = newHandler(); final Throwable cause = new RuntimeException("fake exception"); doAnswer(new Answer<ChannelFuture>() { @Override public ChannelFuture answer(InvocationOnMock invocation) throws Throwable { ChannelPromise promise = invocation.getArgument(4); assertFalse(promise.isVoid()); // This is what DefaultHttp2FrameWriter does... I hate mocking :-(. SimpleChannelPromiseAggregator aggregatedPromise = new SimpleChannelPromiseAggregator(promise, channel, ImmediateEventExecutor.INSTANCE); aggregatedPromise.newPromise(); aggregatedPromise.doneAllocatingPromises(); return aggregatedPromise.setFailure(cause); } }).when(frameWriter).writeGoAway( any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class), any(ChannelPromise.class)); handler.goAway(ctx, STREAM_ID, errorCode, data, newVoidPromise(channel)); verify(pipeline).fireExceptionCaught(cause); }
Example #8
Source File: RedissonTransferQueue.java From redisson with Apache License 2.0 | 6 votes |
public RFuture<V> pollAsync() { TransferQueueServiceImpl s = new TransferQueueServiceImpl(); RFuture<Boolean> future = remoteService.tryExecuteAsync(TransferQueueService.class, s, ImmediateEventExecutor.INSTANCE, -1, null); RPromise<V> result = new RedissonPromise<>(); result.setUncancellable(); future.onComplete((r, e) -> { if (e != null) { result.tryFailure(e); return; } result.trySuccess((V) s.getResult()); }); return result; }
Example #9
Source File: DatagramConnectNotExistsTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
public void testConnectNotExists(Bootstrap cb) throws Throwable { final Promise<Throwable> promise = ImmediateEventExecutor.INSTANCE.newPromise(); cb.handler(new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { promise.trySuccess(cause); } }); ChannelFuture future = cb.connect(NetUtil.LOCALHOST, SocketTestPermutation.BAD_PORT); try { Channel datagramChannel = future.syncUninterruptibly().channel(); Assert.assertTrue(datagramChannel.isActive()); datagramChannel.writeAndFlush( Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII)).syncUninterruptibly(); if (!(datagramChannel instanceof OioDatagramChannel)) { Assert.assertTrue(promise.syncUninterruptibly().getNow() instanceof PortUnreachableException); } } finally { future.channel().close(); } }
Example #10
Source File: StreamMessageDuplicatorTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void raiseExceptionInOnNext() { final DefaultStreamMessage<ByteBuf> publisher = new DefaultStreamMessage<>(); final StreamMessageDuplicator<ByteBuf> duplicator = publisher.toDuplicator(ImmediateEventExecutor.INSTANCE); final ByteBuf buf = newUnpooledBuffer(); publisher.write(buf); assertThat(buf.refCnt()).isOne(); // Release the buf after writing to the publisher which must not happen! buf.release(); final ByteBufSubscriber subscriber = new ByteBufSubscriber(); duplicator.duplicate().subscribe(subscriber, ImmediateEventExecutor.INSTANCE); assertThatThrownBy(() -> subscriber.completionFuture().get()).hasCauseInstanceOf( IllegalReferenceCountException.class); }
Example #11
Source File: StreamMessageDuplicatorTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void closingDuplicatorDoesNotAbortDuplicatedStream() { final DefaultStreamMessage<ByteBuf> publisher = new DefaultStreamMessage<>(); final StreamMessageDuplicator<ByteBuf> duplicator = publisher.toDuplicator(ImmediateEventExecutor.INSTANCE); final ByteBufSubscriber subscriber = new ByteBufSubscriber(); duplicator.duplicate().subscribe(subscriber, ImmediateEventExecutor.INSTANCE); duplicator.close(); // duplicate() is not allowed anymore. assertThatThrownBy(duplicator::duplicate).isInstanceOf(IllegalStateException.class); assertThat(subscriber.completionFuture().isDone()).isFalse(); publisher.close(); assertThat(subscriber.completionFuture().isDone()).isTrue(); }
Example #12
Source File: StreamMessageDuplicatorTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void abortPublisherWithSubscribers() { for (Throwable abortCause : ABORT_CAUSES) { final DefaultStreamMessage<String> publisher = new DefaultStreamMessage<>(); final StreamMessageDuplicator<String> duplicator = publisher.toDuplicator(ImmediateEventExecutor.INSTANCE); final CompletableFuture<String> future = subscribe(duplicator.duplicate()); if (abortCause == null) { publisher.abort(); } else { publisher.abort(abortCause); } if (abortCause == null) { assertThatThrownBy(future::join).hasCauseInstanceOf(AbortedStreamException.class); } else { assertThatThrownBy(future::join).hasCauseInstanceOf(abortCause.getClass()); } duplicator.abort(); } }
Example #13
Source File: StreamMessageDuplicatorTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void subscribeAfterPublisherClosed() throws Exception { final DefaultStreamMessage<String> publisher = new DefaultStreamMessage<>(); final StreamMessageDuplicator<String> duplicator = publisher.toDuplicator(ImmediateEventExecutor.INSTANCE); final CompletableFuture<String> future1 = subscribe(duplicator.duplicate()); writeData(publisher); publisher.close(); assertThat(future1.get()).isEqualTo("Armeria is awesome."); // Still subscribable. final CompletableFuture<String> future2 = subscribe(duplicator.duplicate()); assertThat(future2.get()).isEqualTo("Armeria is awesome."); duplicator.abort(); }
Example #14
Source File: StreamMessageDuplicatorTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void abortPublisherWithoutSubscriber() { for (Throwable abortCause : ABORT_CAUSES) { final DefaultStreamMessage<String> publisher = new DefaultStreamMessage<>(); final StreamMessageDuplicator<String> duplicator = publisher.toDuplicator(ImmediateEventExecutor.INSTANCE); if (abortCause == null) { publisher.abort(); } else { publisher.abort(abortCause); } // Completed exceptionally once a subscriber subscribes. final CompletableFuture<String> future = subscribe(duplicator.duplicate()); if (abortCause == null) { assertThatThrownBy(future::join).hasCauseInstanceOf(AbortedStreamException.class); } else { assertThatThrownBy(future::join).hasCauseInstanceOf(abortCause.getClass()); } duplicator.abort(); } }
Example #15
Source File: DeferredStreamMessageTest.java From armeria with Apache License 2.0 | 6 votes |
@ParameterizedTest @ArgumentsSource(AbortCauseArgumentProvider.class) void testLateAbortWithSubscriber(@Nullable Throwable cause) { final DeferredStreamMessage<Object> m = new DeferredStreamMessage<>(); final DefaultStreamMessage<Object> d = new DefaultStreamMessage<>(); @SuppressWarnings("unchecked") final Subscriber<Object> subscriber = mock(Subscriber.class); m.subscribe(subscriber, ImmediateEventExecutor.INSTANCE); m.delegate(d); verify(subscriber).onSubscribe(any()); if (cause == null) { m.abort(); } else { m.abort(cause); } if (cause == null) { verify(subscriber, times(1)).onError(isA(AbortedStreamException.class)); } else { verify(subscriber, times(1)).onError(isA(cause.getClass())); } assertAborted(m, cause); assertAborted(d, cause); }
Example #16
Source File: DeferredStreamMessageTest.java From armeria with Apache License 2.0 | 6 votes |
@ParameterizedTest @ArgumentsSource(AbortCauseArgumentProvider.class) void testEarlyAbortWithSubscriber(@Nullable Throwable cause) { final DeferredStreamMessage<Object> m = new DeferredStreamMessage<>(); @SuppressWarnings("unchecked") final Subscriber<Object> subscriber = mock(Subscriber.class); m.subscribe(subscriber, ImmediateEventExecutor.INSTANCE); if (cause == null) { m.abort(); } else { m.abort(cause); } assertAborted(m, cause); final DefaultStreamMessage<Object> d = new DefaultStreamMessage<>(); m.delegate(d); assertAborted(d, cause); }
Example #17
Source File: HttpEncodedResponseTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void testLeak() { final ByteBuf buf = Unpooled.buffer(); buf.writeCharSequence("foo", StandardCharsets.UTF_8); final HttpResponse orig = AggregatedHttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, PooledHttpData.wrap(buf).withEndOfStream()).toHttpResponse(); final HttpEncodedResponse encoded = new HttpEncodedResponse( orig, HttpEncodingType.DEFLATE, mediaType -> true, 1); // Drain the stream. encoded.subscribe(NoopSubscriber.get(), ImmediateEventExecutor.INSTANCE); // 'buf' should be released. assertThat(buf.refCnt()).isZero(); }
Example #18
Source File: PublisherBasedStreamMessage.java From armeria with Apache License 2.0 | 6 votes |
private void abort0(Throwable cause) { final AbortableSubscriber subscriber = this.subscriber; if (subscriber != null) { subscriber.abort(cause); return; } final AbortableSubscriber abortable = new AbortableSubscriber(this, AbortingSubscriber.get(cause), ImmediateEventExecutor.INSTANCE, false); if (!subscriberUpdater.compareAndSet(this, null, abortable)) { this.subscriber.abort(cause); return; } abortable.abort(cause); abortable.onSubscribe(NoopSubscription.INSTANCE); }
Example #19
Source File: DefaultStreamMessageDuplicator.java From armeria with Apache License 2.0 | 6 votes |
private void abort0(Throwable cause) { final DownstreamSubscription<T> currentSubscription = subscription; if (currentSubscription != null) { currentSubscription.abort(cause); return; } final DownstreamSubscription<T> newSubscription = new DownstreamSubscription<>( this, AbortingSubscriber.get(cause), processor, ImmediateEventExecutor.INSTANCE, false, false); if (subscriptionUpdater.compareAndSet(this, null, newSubscription)) { newSubscription.whenComplete().completeExceptionally(cause); } else { subscription.abort(cause); } }
Example #20
Source File: ClientConnectionImpl.java From pravega with Apache License 2.0 | 6 votes |
@Override public void sendAsync(List<Append> appends, CompletedCallback callback) { Channel ch; try { checkClientConnectionClosed(); ch = nettyHandler.getChannel(); } catch (ConnectionFailedException e) { callback.complete(new ConnectionFailedException("Connection to " + connectionName + " is not established.")); return; } PromiseCombiner combiner = new PromiseCombiner(ImmediateEventExecutor.INSTANCE); for (Append append : appends) { combiner.add(ch.write(append)); } ch.flush(); ChannelPromise promise = ch.newPromise(); promise.addListener(future -> { nettyHandler.setRecentMessage(); Throwable cause = future.cause(); callback.complete(cause == null ? null : new ConnectionFailedException(cause)); }); combiner.finish(promise); }
Example #21
Source File: StreamMessageDuplicatorTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void closePublisherNormally() throws Exception { final DefaultStreamMessage<String> publisher = new DefaultStreamMessage<>(); final StreamMessageDuplicator<String> duplicator = publisher.toDuplicator(ImmediateEventExecutor.INSTANCE); final CompletableFuture<String> future1 = subscribe(duplicator.duplicate()); final CompletableFuture<String> future2 = subscribe(duplicator.duplicate()); writeData(publisher); publisher.close(); assertThat(future1.get()).isEqualTo("Armeria is awesome."); assertThat(future2.get()).isEqualTo("Armeria is awesome."); duplicator.abort(); }
Example #22
Source File: SmtpSessionTest.java From NioSmtpClient with Apache License 2.0 | 6 votes |
private SslHandler getSslHandler() throws Exception { // get SslHandler if it was added to the pipeline ArgumentCaptor<ChannelHandler> captor = ArgumentCaptor.forClass(ChannelHandler.class); verify(pipeline).addFirst(captor.capture()); SslHandler sslHandler = (SslHandler) captor.getValue(); // mock and store the context so we can get the handshake future ChannelHandlerContext context = mock(ChannelHandlerContext.class); when(context.executor()).thenReturn(ImmediateEventExecutor.INSTANCE); when(context.channel()).thenReturn(mock(Channel.class, Answers.RETURNS_MOCKS.get())); // add the handler but prevent the handshake from running automatically when(channel.isActive()).thenReturn(false); sslHandler.handlerAdded(context); return sslHandler; }
Example #23
Source File: StreamMessageDuplicatorTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void closePublisherExceptionally() throws Exception { final DefaultStreamMessage<String> publisher = new DefaultStreamMessage<>(); final StreamMessageDuplicator<String> duplicator = publisher.toDuplicator(ImmediateEventExecutor.INSTANCE); final CompletableFuture<String> future1 = subscribe(duplicator.duplicate()); final CompletableFuture<String> future2 = subscribe(duplicator.duplicate()); writeData(publisher); publisher.close(clearTrace(new AnticipatedException())); assertThatThrownBy(future1::join).hasCauseInstanceOf(AnticipatedException.class); assertThatThrownBy(future2::join).hasCauseInstanceOf(AnticipatedException.class); duplicator.abort(); }
Example #24
Source File: StreamMessageDuplicatorTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void childStreamIsNotClosedWhenDemandIsNotEnough() throws Exception { final DefaultStreamMessage<String> publisher = new DefaultStreamMessage<>(); final StreamMessageDuplicator<String> duplicator = publisher.toDuplicator(ImmediateEventExecutor.INSTANCE); final CompletableFuture<String> future1 = new CompletableFuture<>(); final StringSubscriber subscriber = new StringSubscriber(future1, 2); final StreamMessage<String> sm = duplicator.duplicate(); sm.whenComplete().whenComplete(subscriber); sm.subscribe(subscriber); final CompletableFuture<String> future2 = subscribe(duplicator.duplicate(), 3); writeData(publisher); publisher.close(); assertThat(future2.get()).isEqualTo("Armeria is awesome."); assertThat(future1.isDone()).isEqualTo(false); subscriber.requestAnother(); assertThat(future1.get()).isEqualTo("Armeria is awesome."); duplicator.abort(); }
Example #25
Source File: DeferredStreamMessageTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void testStreamingError() { final DeferredStreamMessage<String> m = new DeferredStreamMessage<>(); final DefaultStreamMessage<String> d = new DefaultStreamMessage<>(); m.delegate(d); final RecordingSubscriber subscriber = new RecordingSubscriber(); final List<String> recording = subscriber.recording; m.subscribe(subscriber, ImmediateEventExecutor.INSTANCE); assertThat(recording).containsExactly("onSubscribe"); d.write("A"); assertThat(recording).containsExactly("onSubscribe", "A"); final Exception exception = new Exception(); d.close(exception); assertThat(recording).hasSize(3); assertThat(recording.get(2)).startsWith("onError: " + exception); assertThat(m.isOpen()).isFalse(); assertThat(m.isEmpty()).isFalse(); assertThat(m.whenComplete()).hasFailedWithThrowableThat().isSameAs(exception); assertThat(d.isOpen()).isFalse(); assertThat(d.isEmpty()).isFalse(); assertThat(d.whenComplete()).hasFailedWithThrowableThat().isSameAs(exception); }
Example #26
Source File: DefaultStreamMessageTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void abortedStreamCallOnErrorAfterCloseIsCalled() throws InterruptedException { final StreamMessageAndWriter<Object> stream = new DefaultStreamMessage<>(); final PooledHttpData data = PooledHttpData.wrap( PooledByteBufAllocator.DEFAULT.buffer().writeByte(0)).withEndOfStream(); stream.write(data); stream.close(); final AtomicReference<Throwable> throwableCaptor = new AtomicReference<>(); stream.subscribe(new Subscriber<Object>() { @Override public void onSubscribe(Subscription s) {} @Override public void onNext(Object o) {} @Override public void onError(Throwable t) { throwableCaptor.set(t); } @Override public void onComplete() { fail(); } }, ImmediateEventExecutor.INSTANCE); stream.abort(); assertThat(throwableCaptor.get()).isInstanceOf(AbortedStreamException.class); assertThat(data.refCnt()).isZero(); }
Example #27
Source File: XnioEventLoopGroup.java From netty-xnio-transport with Apache License 2.0 | 5 votes |
@Override public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { shutdown(); if (isShutdown()) { return ImmediateEventExecutor.INSTANCE.newSucceededFuture(null); } else { return ImmediateEventExecutor.INSTANCE.newFailedFuture(new TimeoutException()); } }
Example #28
Source File: DefaultStreamMessageTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void abortedStreamCallOnCompleteIfNoData() throws InterruptedException { final StreamMessageAndWriter<Object> stream = new DefaultStreamMessage<>(); stream.close(); final AtomicBoolean onCompleteCalled = new AtomicBoolean(); stream.subscribe(new Subscriber<Object>() { @Override public void onSubscribe(Subscription s) {} @Override public void onNext(Object o) {} @Override public void onError(Throwable t) { fail(); } @Override public void onComplete() { onCompleteCalled.set(true); } }, ImmediateEventExecutor.INSTANCE); stream.abort(); assertThat(onCompleteCalled.get()).isTrue(); }
Example #29
Source File: StreamMessageDuplicatorVerification.java From armeria with Apache License 2.0 | 5 votes |
@Override public StreamMessage<Long> createFailedPublisher() { final StreamMessage<Long> source = new DefaultStreamMessage<>(); final StreamMessageDuplicator<Long> duplicator = source.toDuplicator(ImmediateEventExecutor.INSTANCE); final StreamMessage<Long> duplicate = duplicator.duplicate(); duplicate.subscribe(new NoopSubscriber<>()); return duplicate; }
Example #30
Source File: StreamMessageDuplicatorVerification.java From armeria with Apache License 2.0 | 5 votes |
@Override public StreamMessage<Long> createAbortedPublisher(long elements) { final StreamMessage<Long> source = createStreamMessage(elements + 1, false); final StreamMessageDuplicator<Long> duplicator = source.toDuplicator(ImmediateEventExecutor.INSTANCE); final StreamMessage<Long> duplicate = duplicator.duplicate(); if (elements == 0) { duplicate.abort(); return duplicate; } return new StreamMessageWrapper<Long>(duplicate) { @Override public void subscribe(Subscriber<? super Long> subscriber) { super.subscribe(new Subscriber<Long>() { @Override public void onSubscribe(Subscription s) { subscriber.onSubscribe(s); } @Override public void onNext(Long value) { subscriber.onNext(value); if (value == elements) { duplicate.abort(); } } @Override public void onError(Throwable cause) { subscriber.onError(cause); } @Override public void onComplete() { subscriber.onComplete(); } }); } }; }