io.netty.util.concurrent.EventExecutor Java Examples

The following examples show how to use io.netty.util.concurrent.EventExecutor. 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: AbstractChannelHandlerContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
static void invokeChannelWritabilityChanged(final AbstractChannelHandlerContext next) {
    EventExecutor executor = next.executor();
    if (executor.inEventLoop()) {
        next.invokeChannelWritabilityChanged();
    } else {
        Runnable task = next.invokeChannelWritableStateChangedTask;
        if (task == null) {
            next.invokeChannelWritableStateChangedTask = task = new Runnable() {
                @Override
                public void run() {
                    next.invokeChannelWritabilityChanged();
                }
            };
        }
        executor.execute(task);
    }
}
 
Example #2
Source File: SslHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Performs TLS renegotiation.
 */
public Future<Channel> renegotiate(final Promise<Channel> promise) {
    if (promise == null) {
        throw new NullPointerException("promise");
    }

    ChannelHandlerContext ctx = this.ctx;
    if (ctx == null) {
        throw new IllegalStateException();
    }

    EventExecutor executor = ctx.executor();
    if (!executor.inEventLoop()) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                handshake(promise);
            }
        });
        return promise;
    }

    handshake(promise);
    return promise;
}
 
Example #3
Source File: DefaultStreamMessageDuplicator.java    From armeria with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
StreamMessageProcessor(DefaultStreamMessageDuplicator<T> duplicator, StreamMessage<T> upstream,
                       SignalLengthGetter<?> signalLengthGetter,
                       EventExecutor executor, long maxSignalLength) {
    this.duplicator = duplicator;
    this.upstream = upstream;
    this.signalLengthGetter = (SignalLengthGetter<Object>) signalLengthGetter;
    this.executor = executor;
    if (maxSignalLength == 0 || maxSignalLength > Integer.MAX_VALUE) {
        this.maxSignalLength = Integer.MAX_VALUE;
    } else {
        this.maxSignalLength = (int) maxSignalLength;
    }
    signals = new SignalQueue(this.signalLengthGetter);
    upstream.subscribe(this, executor,
                       WITH_POOLED_OBJECTS, SubscriptionOption.NOTIFY_CANCELLATION);
}
 
Example #4
Source File: AbstractChannelHandlerContext.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelHandlerContext fireUserEventTriggered(final Object event) {
    if (event == null) {
        throw new NullPointerException("event");
    }

    final AbstractChannelHandlerContext next = findContextInbound();
    EventExecutor executor = next.executor();
    if (executor.inEventLoop()) {
        next.invokeUserEventTriggered(event);
    } else {
        executor.execute(new OneTimeTask() {
            @Override
            public void run() {
                next.invokeUserEventTriggered(event);
            }
        });
    }
    return this;
}
 
Example #5
Source File: MqttInflightResenderChannelHandler.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
private void initialize(ChannelHandlerContext ctx) {
    // Avoid the case where destroy() is called before scheduling timeouts.
    // See: https://github.com/netty/netty/issues/143
    if (logger.isDebugEnabled()) {
        logger.debug("Initializing autoflush handler on channel {}", ctx.channel());
    }
    switch (state) {
        case 1:
        case 2:
            return;
        default:
            break;
    }

    state = 1;

    EventExecutor loop = ctx.executor();

    lastExecutionTime = System.nanoTime();
    resenderTimeout = loop.schedule(new WriterIdleTimeoutTask(ctx), resenderTimeNanos, TimeUnit.NANOSECONDS);
}
 
Example #6
Source File: Bzip2Encoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Close this {@link Bzip2Encoder} and so finish the encoding.
 * The given {@link ChannelFuture} will be notified once the operation
 * completes and will also be returned.关闭这个Bzip2Encoder,然后完成编码。一旦操作完成,给定的ChannelFuture将被通知,并且也将被返回。
 */
public ChannelFuture close(final ChannelPromise promise) {
    ChannelHandlerContext ctx = ctx();
    EventExecutor executor = ctx.executor();
    if (executor.inEventLoop()) {
        return finishEncode(ctx, promise);
    } else {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                ChannelFuture f = finishEncode(ctx(), promise);
                f.addListener(new ChannelPromiseNotifier(promise));
            }
        });
        return promise;
    }
}
 
Example #7
Source File: AutoFlushHandler.java    From cassandana with Apache License 2.0 6 votes vote down vote up
private void initialize(ChannelHandlerContext ctx) {
    // Avoid the case where destroy() is called before scheduling timeouts.
    // See: https://github.com/netty/netty/issues/143
    if (LOG.isDebugEnabled()) {
        LOG.debug("Initializing autoflush handler on channel {} Cid: {}", ctx.channel(),
                  NettyUtils.clientID(ctx.channel()));
    }
    switch (state) {
        case 1:
        case 2:
            return;
    }

    state = 1;

    EventExecutor loop = ctx.executor();

    lastWriteTime = System.nanoTime();
    writerIdleTimeout = loop.schedule(new WriterIdleTimeoutTask(ctx), writerIdleTimeNanos, TimeUnit.NANOSECONDS);
}
 
Example #8
Source File: InflightResender.java    From cassandana with Apache License 2.0 6 votes vote down vote up
private void initialize(ChannelHandlerContext ctx) {
    // Avoid the case where destroy() is called before scheduling timeouts.
    // See: https://github.com/netty/netty/issues/143
    if (LOG.isDebugEnabled()) {
        LOG.debug("Initializing autoflush handler on channel {}", ctx.channel());
    }
    switch (state) {
        case 1:
        case 2:
            return;
    }

    state = 1;

    EventExecutor loop = ctx.executor();

    lastExecutionTime = System.nanoTime();
    resenderTimeout = loop.schedule(new WriterIdleTimeoutTask(ctx), resenderTimeNanos, TimeUnit.NANOSECONDS);
}
 
Example #9
Source File: ClientConnectionsShutdown.java    From zuul with Apache License 2.0 6 votes vote down vote up
public ClientConnectionsShutdown(ChannelGroup channels, EventExecutor executor, EurekaClient discoveryClient)
    {
        this.channels = channels;
        this.executor = executor;
        this.discoveryClient = discoveryClient;

        if (discoveryClient != null) {
            initDiscoveryListener();
        }

        // Only uncomment this for local testing!
        // Allow a fast property to invoke connection shutdown for testing purposes.
//        DynamicBooleanProperty DEBUG_SHUTDOWN = new DynamicBooleanProperty("server.outofservice.connections.shutdown.debug", false);
//        DEBUG_SHUTDOWN.addCallback(() -> {
//            if (DEBUG_SHUTDOWN.get()) {
//                gracefullyShutdownClientChannels();
//            }
//        });
    }
 
Example #10
Source File: AbstractChannelHandlerContext.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture deregister(final ChannelPromise promise) {
    if (!validatePromise(promise, false)) {
        // cancelled
        return promise;
    }

    final AbstractChannelHandlerContext next = findContextOutbound();
    EventExecutor executor = next.executor();
    if (executor.inEventLoop()) {
        next.invokeDeregister(promise);
    } else {
        safeExecute(executor, new OneTimeTask() {
            @Override
            public void run() {
                next.invokeDeregister(promise);
            }
        }, promise, null);
    }

    return promise;
}
 
Example #11
Source File: AbstractChannelHandlerContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
static void invokeExceptionCaught(final AbstractChannelHandlerContext next, final Throwable cause) {
    ObjectUtil.checkNotNull(cause, "cause");
    EventExecutor executor = next.executor();
    if (executor.inEventLoop()) {
        next.invokeExceptionCaught(cause);
    } else {
        try {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    next.invokeExceptionCaught(cause);
                }
            });
        } catch (Throwable t) {
            if (logger.isWarnEnabled()) {
                logger.warn("Failed to submit an exceptionCaught() event.", t);
                logger.warn("The exceptionCaught() event that was failed to submit was:", cause);
            }
        }
    }
}
 
Example #12
Source File: JZlibEncoder.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture close(final ChannelPromise promise) {
    ChannelHandlerContext ctx = ctx();
    EventExecutor executor = ctx.executor();
    if (executor.inEventLoop()) {
        return finishEncode(ctx, promise);
    } else {
        final ChannelPromise p = ctx.newPromise();
        executor.execute(new Runnable() {
            @Override
            public void run() {
                ChannelFuture f = finishEncode(ctx(), p);
                f.addListener(new ChannelPromiseNotifier(promise));
            }
        });
        return p;
    }
}
 
Example #13
Source File: SimpleNonceManager.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private boolean addInvalidNonce(final Nonce nonce, final EventExecutor executor) {
    long now = System.currentTimeMillis();
    long invalidBefore = now - firstUseTimeOut;

    long timeTillInvalid = nonce.timeStamp - invalidBefore;
    if (timeTillInvalid > 0) {
        if (invalidNonces.add(nonce.nonce)) {
            executor.schedule(new InvalidNonceCleaner(nonce.nonce), timeTillInvalid, TimeUnit.MILLISECONDS);
            return true;
        } else {
            return false;
        }
    } else {
        // So close to expiring any record of this nonce being used could have been cleared so
        // don't take a chance and just say no.
        return false;
    }
}
 
Example #14
Source File: AbstractChannelHandlerContext.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture bind(final SocketAddress localAddress, final ChannelPromise promise) {
    if (localAddress == null) {
        throw new NullPointerException("localAddress");
    }
    if (!validatePromise(promise, false)) {
        // cancelled
        return promise;
    }

    final AbstractChannelHandlerContext next = findContextOutbound();
    EventExecutor executor = next.executor();
    if (executor.inEventLoop()) {
        next.invokeBind(localAddress, promise);
    } else {
        safeExecute(executor, new OneTimeTask() {
            @Override
            public void run() {
                next.invokeBind(localAddress, promise);
            }
        }, promise, null);
    }

    return promise;
}
 
Example #15
Source File: ProxyRouterEndpointExecutionHandler.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Override
public void unrecoverableErrorOccurred(Throwable error, boolean guaranteesBrokenDownstreamResponse) {
    // Cancel request streaming so it stops trying to send data downstream and releases any chunks we've been
    //      holding onto. This holds true no matter the value of guaranteesBrokenDownstreamResponse
    //      (i.e. we want to stop sending data downstream no matter what). Note that this does not stop the
    //      downstream call's response, and that is intentional to support use cases where the downstream
    //      system can still successfully send a full response even though the request wasn't fully sent.
    proxyRouterProcessingState.cancelRequestStreaming(error, ctx);

    setDownstreamCallTimeOnRequestAttributesIfNotAlreadyDone();

    EventExecutor executor = ctx.executor();
    if (executor.inEventLoop()) {
        sendUnrecoverableErrorDownPipeline(error, guaranteesBrokenDownstreamResponse);
    }
    else {
        executor.execute(() -> sendUnrecoverableErrorDownPipeline(error, guaranteesBrokenDownstreamResponse));
    }
}
 
Example #16
Source File: DefaultChannelHandlerContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
DefaultChannelHandlerContext(
        DefaultChannelPipeline pipeline, EventExecutor executor, String name, ChannelHandler handler) {
    super(pipeline, executor, name, isInbound(handler), isOutbound(handler));
    if (handler == null) {
        throw new NullPointerException("handler");
    }
    this.handler = handler;
}
 
Example #17
Source File: FailedChannelFuture.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance.
 *
 * @param channel the {@link Channel} associated with this future
 * @param cause   the cause of failure
 */
FailedChannelFuture(Channel channel, EventExecutor executor, Throwable cause) {
    super(channel, executor);
    if (cause == null) {
        throw new NullPointerException("cause");
    }
    this.cause = cause;
}
 
Example #18
Source File: DefaultChannelGroupFuture.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
DefaultChannelGroupFuture(ChannelGroup group, Map<Channel, ChannelFuture> futures, EventExecutor executor) {
    super(executor);
    this.group = group;
    this.futures = Collections.unmodifiableMap(futures);
    for (ChannelFuture f: this.futures.values()) {
        f.addListener(childListener);
    }

    // Done on arrival?
    if (this.futures.isEmpty()) {
        setSuccess0();
    }
}
 
Example #19
Source File: CompleteChannelFuture.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected EventExecutor executor() {
    EventExecutor e = super.executor();
    if (e == null) {
        return channel().eventLoop();
    } else {
        return e;
    }
}
 
Example #20
Source File: JumbuneAgentDecoder.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Invoke log files receive handler.
 *
 * @param ctx the ctx
 */
private void invokeLogFilesReceiveHandlerForHA(ChannelHandlerContext ctx) {
	ChannelPipeline p = ctx.pipeline();		
	EventExecutor e1 = new DefaultEventExecutorGroup(1).next();
	p.addLast("stringDecoder", new StringDecoder());
	p.addLast("delegator", new Delegator(receiveDirectory));
	p.addLast(HEARTBEAT_HANDLER, new HeartbeatHandler(JumbuneAgent.getHeartBeatMillis(), 
			JumbuneAgent.getHeartBeatMillis(), JumbuneAgent.getHeartBeatMillis()));
	p.addLast("stringEncoder", new StringEncoder());
	p.addLast(e1, new LogFilesEncoder());
	p.remove(this);
}
 
Example #21
Source File: ThreadPerChannelEventLoopGroupTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void runTest(ThreadPerChannelEventLoopGroup loopGroup) throws InterruptedException {
    int taskCount = 100;
    EventExecutor testExecutor = new TestEventExecutor();
    ChannelGroup channelGroup = new DefaultChannelGroup(testExecutor);
    while (taskCount-- > 0) {
        Channel channel = new EmbeddedChannel(NOOP_HANDLER);
        loopGroup.register(new DefaultChannelPromise(channel, testExecutor));
        channelGroup.add(channel);
    }
    channelGroup.close().sync();
    loopGroup.shutdownGracefully(100, 200, TimeUnit.MILLISECONDS).sync();
    assertTrue(loopGroup.isTerminated());
}
 
Example #22
Source File: DefaultChannelPromise.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected EventExecutor executor() {
    EventExecutor e = super.executor();
    if (e == null) {
        return channel().eventLoop();
    } else {
        return e;
    }
}
 
Example #23
Source File: DefaultChannelPipeline.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private void destroyDown(Thread currentThread, AbstractChannelHandlerContext ctx, boolean inEventLoop) {
    // We have reached at tail; now traverse backwards.
    final AbstractChannelHandlerContext head = this.head;
    for (;;) {
        if (ctx == head) {
            break;
        }

        final EventExecutor executor = ctx.executor();
        if (inEventLoop || executor.inEventLoop(currentThread)) {
            synchronized (this) {
                remove0(ctx);
            }
            callHandlerRemoved0(ctx);
        } else {
            final AbstractChannelHandlerContext finalCtx = ctx;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    destroyDown(Thread.currentThread(), finalCtx, true);
                }
            });
            break;
        }

        ctx = ctx.prev;
        inEventLoop = false;
    }
}
 
Example #24
Source File: ThriftClientHandler.java    From drift with Apache License 2.0 5 votes vote down vote up
void registerRequestTimeout(EventExecutor executor)
{
    try {
        timeout.set(executor.schedule(
                () -> onChannelError(new RequestTimeoutException("Timed out waiting " + requestTimeout + " to receive response")),
                requestTimeout.toMillis(),
                MILLISECONDS));
    }
    catch (Throwable throwable) {
        onChannelError(new TTransportException("Unable to schedule request timeout", throwable));
        throw throwable;
    }
}
 
Example #25
Source File: DefaultStreamMessageDuplicator.java    From armeria with Apache License 2.0 5 votes vote down vote up
DownstreamSubscription(ChildStreamMessage<T> streamMessage,
                       Subscriber<? super T> subscriber, StreamMessageProcessor<T> processor,
                       EventExecutor executor, boolean withPooledObjects, boolean notifyCancellation) {
    this.streamMessage = streamMessage;
    this.subscriber = subscriber;
    this.processor = processor;
    this.executor = executor;
    this.withPooledObjects = withPooledObjects;
    this.notifyCancellation = notifyCancellation;
}
 
Example #26
Source File: AbstractChannelHandlerContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public EventExecutor executor() {
    if (executor == null) {
        return channel().eventLoop();
    } else {
        return executor;
    }
}
 
Example #27
Source File: AbstractChannelHandlerContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
    public ChannelFuture connect(
            final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) {

        if (remoteAddress == null) {
            throw new NullPointerException("remoteAddress");
        }
        if (isNotValidPromise(promise, false)) {
            // cancelled
            return promise;
        }

//        找到pipeline中tail节点的上一个节点
        final AbstractChannelHandlerContext next = findContextOutbound();
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
//            执行connect
            next.invokeConnect(remoteAddress, localAddress, promise);
        } else {
            safeExecute(executor, new Runnable() {
                @Override
                public void run() {
                    next.invokeConnect(remoteAddress, localAddress, promise);
                }
            }, promise, null);
        }
        return promise;
    }
 
Example #28
Source File: AbstractChannelHandlerContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
static void invokeChannelUnregistered(final AbstractChannelHandlerContext next) {
    EventExecutor executor = next.executor();
    if (executor.inEventLoop()) {
        next.invokeChannelUnregistered();
    } else {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                next.invokeChannelUnregistered();
            }
        });
    }
}
 
Example #29
Source File: AbstractChannelHandlerContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
static void invokeUserEventTriggered(final AbstractChannelHandlerContext next, final Object event) {
    ObjectUtil.checkNotNull(event, "event");
    EventExecutor executor = next.executor();
    if (executor.inEventLoop()) {
        next.invokeUserEventTriggered(event);
    } else {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                next.invokeUserEventTriggered(event);
            }
        });
    }
}
 
Example #30
Source File: AbstractChannelHandlerContext.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelFuture connect(
        final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) {

    if (remoteAddress == null) {
        throw new NullPointerException("remoteAddress");
    }
    if (!validatePromise(promise, false)) {
        // cancelled
        return promise;
    }

    final AbstractChannelHandlerContext next = findContextOutbound();
    EventExecutor executor = next.executor();
    if (executor.inEventLoop()) {
        next.invokeConnect(remoteAddress, localAddress, promise);
    } else {
        safeExecute(executor, new OneTimeTask() {
            @Override
            public void run() {
                next.invokeConnect(remoteAddress, localAddress, promise);
            }
        }, promise, null);
    }

    return promise;
}