Java Code Examples for io.netty.util.concurrent.ImmediateEventExecutor#INSTANCE

The following examples show how to use io.netty.util.concurrent.ImmediateEventExecutor#INSTANCE . 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: ClientConnectionImpl.java    From pravega with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: DefaultStreamMessageDuplicator.java    From armeria with Apache License 2.0 6 votes vote down vote up
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 3
Source File: ReactorNettyTcpClient.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * A variant of {@link #ReactorNettyTcpClient(String, int, ReactorNettyCodec)}
 * that still manages the lifecycle of the {@link TcpClient} and underlying
 * resources, but allows for direct configuration of other properties of the
 * client through a {@code Function<TcpClient, TcpClient>}.
 * @param clientConfigurer the configurer function
 * @param codec for encoding and decoding the input/output byte streams
 * @since 5.1.3
 * @see org.springframework.messaging.simp.stomp.StompReactorNettyCodec
 */
public ReactorNettyTcpClient(Function<TcpClient, TcpClient> clientConfigurer, ReactorNettyCodec<P> codec) {
	Assert.notNull(codec, "ReactorNettyCodec is required");

	this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
	this.loopResources = LoopResources.create("tcp-client-loop");
	this.poolResources = ConnectionProvider.elastic("tcp-client-pool");
	this.codec = codec;

	this.tcpClient = clientConfigurer.apply(TcpClient
			.create(this.poolResources)
			.runOn(this.loopResources, false)
			.doOnConnected(conn -> this.channelGroup.add(conn.channel())));
}
 
Example 4
Source File: DefaultChannelGroupFuture.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected void checkDeadLock() {
    EventExecutor e = executor();
    if (e != null && e != ImmediateEventExecutor.INSTANCE && e.inEventLoop()) {
        throw new BlockingOperationException();
    }
}
 
Example 5
Source File: SmtpSessionTest.java    From NioSmtpClient with Apache License 2.0 5 votes vote down vote up
private void assertExceptionsFiredOnFailure() throws Exception {
  // get the listener added when the channel was written to
  ArgumentCaptor<ChannelFutureListener> captor = ArgumentCaptor.forClass(ChannelFutureListener.class);
  verify(writeFuture, atLeast(1)).addListener(captor.capture());
  ChannelFutureListener addedListener = captor.getValue();

  // tell the listener the write failed
  DefaultChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
  promise.setFailure(new Exception());
  addedListener.operationComplete(promise);

  verify(pipeline).fireExceptionCaught(promise.cause());
}
 
Example 6
Source File: SmtpSessionTest.java    From NioSmtpClient with Apache License 2.0 5 votes vote down vote up
@Test
public void itClosesTheUnderlyingChannel() {
  DefaultChannelPromise channelPromise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
  when(channel.close()).thenReturn(channelPromise);

  CompletableFuture<Void> f = session.close();
  channelPromise.setSuccess();

  assertThat(f.isDone());
}
 
Example 7
Source File: ChannelsHolder.java    From leo-im-server with Apache License 2.0 5 votes vote down vote up
/**
 * 将channel添加到GroupChannel中
 * @param groupId
 * @param channel
 */
public static void addChannelToGroup(String groupId, Channel channel) {
    DefaultChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
    ChannelGroup returnChannelGroup = CHANNEL_GROUPS.putIfAbsent(groupId, channelGroup);
    if(returnChannelGroup == null) {
        // 不存在该ChannelGroup,第一次添加。
        channelGroup.add(channel);
        return;
    }
    // ChannelGroup已经存在
    returnChannelGroup.add(channel);
}
 
Example 8
Source File: ReactorNettyTcpClient.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Simple constructor with the host and port to use to connect to.
 * <p>This constructor manages the lifecycle of the {@link TcpClient} and
 * underlying resources such as {@link ConnectionProvider},
 * {@link LoopResources}, and {@link ChannelGroup}.
 * <p>For full control over the initialization and lifecycle of the
 * TcpClient, use {@link #ReactorNettyTcpClient(TcpClient, ReactorNettyCodec)}.
 * @param host the host to connect to
 * @param port the port to connect to
 * @param codec for encoding and decoding the input/output byte streams
 * @see org.springframework.messaging.simp.stomp.StompReactorNettyCodec
 */
public ReactorNettyTcpClient(String host, int port, ReactorNettyCodec<P> codec) {
	Assert.notNull(host, "host is required");
	Assert.notNull(codec, "ReactorNettyCodec is required");

	this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
	this.loopResources = LoopResources.create("tcp-client-loop");
	this.poolResources = ConnectionProvider.elastic("tcp-client-pool");
	this.codec = codec;

	this.tcpClient = TcpClient.create(this.poolResources)
			.host(host).port(port)
			.runOn(this.loopResources, false)
			.doOnConnected(conn -> this.channelGroup.add(conn.channel()));
}
 
Example 9
Source File: ReactorNettyTcpClient.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Simple constructor with the host and port to use to connect to.
 * <p>This constructor manages the lifecycle of the {@link TcpClient} and
 * underlying resources such as {@link ConnectionProvider},
 * {@link LoopResources}, and {@link ChannelGroup}.
 * <p>For full control over the initialization and lifecycle of the
 * TcpClient, use {@link #ReactorNettyTcpClient(TcpClient, ReactorNettyCodec)}.
 * @param host the host to connect to
 * @param port the port to connect to
 * @param codec for encoding and decoding the input/output byte streams
 * @see org.springframework.messaging.simp.stomp.StompReactorNettyCodec
 */
public ReactorNettyTcpClient(String host, int port, ReactorNettyCodec<P> codec) {
	Assert.notNull(host, "host is required");
	Assert.notNull(codec, "ReactorNettyCodec is required");

	this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
	this.loopResources = LoopResources.create("tcp-client-loop");
	this.poolResources = ConnectionProvider.elastic("tcp-client-pool");
	this.codec = codec;

	this.tcpClient = TcpClient.create(this.poolResources)
			.host(host).port(port)
			.runOn(this.loopResources, false)
			.doOnConnected(conn -> this.channelGroup.add(conn.channel()));
}
 
Example 10
Source File: DefaultChannelGroupFuture.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void checkDeadLock() {
    EventExecutor e = executor();
    if (e != null && e != ImmediateEventExecutor.INSTANCE && e.inEventLoop()) {
        throw new BlockingOperationException();
    }
}
 
Example 11
Source File: DefaultHttp2FrameWriterTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    frameWriter = new DefaultHttp2FrameWriter();

    outbound = Unpooled.buffer();

    expectedOutbound = Unpooled.EMPTY_BUFFER;

    promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);

    http2HeadersEncoder = new DefaultHttp2HeadersEncoder();

    Answer<Object> answer = new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock var1) throws Throwable {
            Object msg = var1.getArgument(0);
            if (msg instanceof ByteBuf) {
                outbound.writeBytes((ByteBuf) msg);
            }
            ReferenceCountUtil.release(msg);
            return future;
        }
    };
    when(ctx.write(any())).then(answer);
    when(ctx.write(any(), any(ChannelPromise.class))).then(answer);
    when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    when(ctx.channel()).thenReturn(channel);
    when(ctx.executor()).thenReturn(ImmediateEventExecutor.INSTANCE);
}
 
Example 12
Source File: FixedStreamMessage.java    From armeria with Apache License 2.0 5 votes vote down vote up
private void abort0(Throwable cause) {
    final SubscriptionImpl currentSubscription = subscription;
    if (currentSubscription != null) {
        cancelOrAbort(cause);
        return;
    }

    final SubscriptionImpl newSubscription = new SubscriptionImpl(
            this, AbortingSubscriber.get(cause), ImmediateEventExecutor.INSTANCE, false, false);
    subscriptionUpdater.compareAndSet(this, null, newSubscription);
    cancelOrAbort(cause);
}
 
Example 13
Source File: NettyTelnetBootstrap.java    From termd with Apache License 2.0 4 votes vote down vote up
public NettyTelnetBootstrap() {
  this.group = new NioEventLoopGroup();
  this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
}
 
Example 14
Source File: DefaultChannelPromiseTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Test(expected = NullPointerException.class)
public void testNullChannelWithExecutor() {
    new DefaultChannelPromise(null, ImmediateEventExecutor.INSTANCE);
}
 
Example 15
Source File: NettyTelnetBootstrap.java    From termd with Apache License 2.0 4 votes vote down vote up
public NettyTelnetBootstrap() {
  this.group = new NioEventLoopGroup();
  this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
}
 
Example 16
Source File: NettyHttpTelnetBootstrap.java    From arthas with Apache License 2.0 4 votes vote down vote up
public NettyHttpTelnetBootstrap(EventExecutorGroup workerGroup) {
    this.workerGroup = workerGroup;
    this.group = new NioEventLoopGroup();
    this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
}
 
Example 17
Source File: StreamBufferingEncoderTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private ChannelPromise newPromise() {
    return new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
}
 
Example 18
Source File: DefaultHttp2ConnectionEncoderTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private ChannelPromise newPromise() {
    return new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
}
 
Example 19
Source File: NettyTelnetBootstrap.java    From aesh-readline with Apache License 2.0 4 votes vote down vote up
public NettyTelnetBootstrap() {
  this.group = new NioEventLoopGroup();
  this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
}
 
Example 20
Source File: ClientConnectionsShutdown.java    From zuul with Apache License 2.0 4 votes vote down vote up
/**
 * Note this blocks until all the channels have finished closing.
 */
public void gracefullyShutdownClientChannels()
{
    LOG.warn("Gracefully shutting down all client channels");
    try {


        // Mark all active connections to be closed after next response sent.
        LOG.warn("Flagging CLOSE_AFTER_RESPONSE on " + channels.size() + " client channels.");
        // Pick some arbitrary executor.
        PromiseCombiner closeAfterPromises = new PromiseCombiner(ImmediateEventExecutor.INSTANCE);
        for (Channel channel : channels)
        {
            ConnectionCloseType.setForChannel(channel, ConnectionCloseType.DELAYED_GRACEFUL);

            ChannelPromise closePromise = channel.pipeline().newPromise();
            channel.attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE).set(closePromise);
            // TODO(carl-mastrangelo): remove closePromise, since I don't think it's needed.  Need to verify.
            closeAfterPromises.add(channel.closeFuture());
        }

        // Wait for all of the attempts to close connections gracefully, or max of 30 secs each.
        Promise<Void> combinedCloseAfterPromise = executor.newPromise();
        closeAfterPromises.finish(combinedCloseAfterPromise);
        combinedCloseAfterPromise.await(30, TimeUnit.SECONDS);

        // Close all of the remaining active connections.
        LOG.warn("Closing remaining active client channels.");
        List<ChannelFuture> forceCloseFutures = new ArrayList<>();
        channels.forEach(channel -> {
            if (channel.isActive()) {
                ChannelFuture f = channel.pipeline().close();
                forceCloseFutures.add(f);
            }
        });

        LOG.warn("Waiting for " + forceCloseFutures.size() + " client channels to be closed.");
        PromiseCombiner closePromisesCombiner = new PromiseCombiner(ImmediateEventExecutor.INSTANCE);
        closePromisesCombiner.addAll(forceCloseFutures.toArray(new ChannelFuture[0]));
        Promise<Void> combinedClosePromise = executor.newPromise();
        closePromisesCombiner.finish(combinedClosePromise);
        combinedClosePromise.await(5, TimeUnit.SECONDS);
        LOG.warn(forceCloseFutures.size() + " client channels closed.");
    }
    catch (InterruptedException ie) {
        LOG.warn("Interrupted while shutting down client channels");
    }
}