Java Code Examples for io.netty.util.concurrent.ScheduledFuture#cancel()

The following examples show how to use io.netty.util.concurrent.ScheduledFuture#cancel() . 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: DnsQueryContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private void setSuccess(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope) {
    parent.queryContextManager.remove(nameServerAddr(), id);

    // Cancel the timeout task.
    final ScheduledFuture<?> timeoutFuture = this.timeoutFuture;
    if (timeoutFuture != null) {
        timeoutFuture.cancel(false);
    }

    Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> promise = this.promise;
    if (promise.setUncancellable()) {
        @SuppressWarnings("unchecked")
        AddressedEnvelope<DnsResponse, InetSocketAddress> castResponse =
                (AddressedEnvelope<DnsResponse, InetSocketAddress>) envelope.retain();
        if (!promise.trySuccess(castResponse)) {
            // We failed to notify the promise as it was failed before, thus we need to release the envelope
            envelope.release();
        }
    }
}
 
Example 2
Source File: FlowHandler.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);
    Channel ch = ctx.channel();
    channel.set(ch);
    log.info("Connection established with endpoint {} on channel {}", connectionName, ch);
    ch.writeAndFlush(new WireCommands.Hello(WireCommands.WIRE_VERSION, WireCommands.OLDEST_COMPATIBLE_VERSION), ch.voidPromise());
    registeredFutureLatch.release(null); //release all futures waiting for channel registration to complete.
    // WireCommands.KeepAlive messages are sent for every network connection to a SegmentStore.
    ScheduledFuture<?> old = keepAliveFuture.getAndSet(ch.eventLoop()
                                                         .scheduleWithFixedDelay(keepAlive,
                                                                                 KEEP_ALIVE_TIMEOUT_SECONDS,
                                                                                 KEEP_ALIVE_TIMEOUT_SECONDS,
                                                                                 TimeUnit.SECONDS));
    if (old != null) {
        old.cancel(false);
    }
}
 
Example 3
Source File: FlowHandler.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Invoke all the {@link ReplyProcessor#connectionDropped()} for all the registered flows once the
 * connection is disconnected.
 *
 * @see io.netty.channel.ChannelInboundHandler#channelUnregistered(ChannelHandlerContext)
 */
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    ScheduledFuture<?> future = keepAliveFuture.get();
    if (future != null) {
        future.cancel(false);
    }
    channel.set(null);
    log.info("Connection drop observed with endpoint {}", connectionName);
    flowIdReplyProcessorMap.forEach((flowId, rp) -> {
        try {
            log.debug("Connection dropped for flow id {}", flowId);
            rp.connectionDropped();
        } catch (Exception e) {
            // Suppressing exception which prevents all ReplyProcessor.connectionDropped from being invoked.
            log.warn("Encountered exception invoking ReplyProcessor for flow id {}", flowId, e);
        }
    });
    registeredFutureLatch.releaseExceptionally(new ConnectionClosedException());
    super.channelUnregistered(ctx);
}
 
Example 4
Source File: RequestMuxer.java    From xio with Apache License 2.0 6 votes vote down vote up
@Override
public void close() {
  isRunning.set(false);
  for (ScheduledFuture<?> f : scheduledFutures) {
    f.cancel(true);
  }

  // wait for scheduled futures to cancel
  while (scheduledFutures.stream().anyMatch((f) -> !f.isDone())) {
    Uninterruptibles.sleepUninterruptibly(250, TimeUnit.MILLISECONDS);
  }

  // handle remaining items in the queue
  while (counter.get() > 0) {
    drainMessageQ();
  }

  connectionPool.close();
}
 
Example 5
Source File: AsyncContextImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public void updateTimeout() {
    ScheduledFuture<?> key = this.timeoutKey;
    if (key != null) {
        if (!key.cancel(false)) {
            return;
        } else {
            this.timeoutKey = null;
        }
    }
    if (timeout > 0 && !complete) {
        this.timeoutKey = exchange.getIoThread().schedule(timeoutTask, timeout, TimeUnit.MILLISECONDS);
    }
}
 
Example 6
Source File: ThriftClientHandler.java    From drift with Apache License 2.0 5 votes vote down vote up
private void cancelRequestTimeout()
{
    ScheduledFuture<?> timeout = this.timeout.get();
    if (timeout != null) {
        timeout.cancel(false);
    }
}
 
Example 7
Source File: HealthCheckedChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Validate that the channel returned by the underlying channel pool is healthy. If so, complete the result future with the
 * channel returned by the underlying pool. If not, close the channel and try to get a different one.
 *
 * @param delegateFuture A completed promise as a result of invoking delegate.acquire().
 * @param resultFuture The future that should be completed with the healthy, acquired channel.
 * @param timeoutFuture The future for the timeout task. This future will be cancelled when a channel is acquired.
 */
private void ensureAcquiredChannelIsHealthy(Promise<Channel> delegateFuture,
                                            Promise<Channel> resultFuture,
                                            ScheduledFuture<?> timeoutFuture) {
    // If our delegate failed to connect, forward down the failure. Don't try again.
    if (!delegateFuture.isSuccess()) {
        timeoutFuture.cancel(false);
        resultFuture.tryFailure(delegateFuture.cause());
        return;
    }

    // If our delegate gave us an unhealthy connection, close it and try to get a new one.
    Channel channel = delegateFuture.getNow();
    if (!isHealthy(channel)) {
        channel.close();
        delegate.release(channel);
        tryAcquire(resultFuture, timeoutFuture);
        return;
    }

    // Cancel the timeout (best effort), and return back the healthy channel.
    timeoutFuture.cancel(false);
    if (!resultFuture.trySuccess(channel)) {
        // If we couldn't give the channel to the result future (because it failed for some other reason),
        // just return it to the pool.
        release(channel);
    }
}
 
Example 8
Source File: AbstractConcurrencyLimitingClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    isRun = true;

    final ScheduledFuture<?> timeoutFuture = get();
    if (timeoutFuture != null) {
        if (timeoutFuture.isDone() || !timeoutFuture.cancel(false)) {
            // Timeout task ran already or is determined to run.
            numActiveRequests.decrementAndGet();
            return;
        }
    }

    try (SafeCloseable ignored = ctx.replace()) {
        try {
            final O actualRes = unwrap().execute(ctx, req);
            actualRes.whenComplete().handleAsync((unused, cause) -> {
                numActiveRequests.decrementAndGet();
                drain();
                return null;
            }, ctx.eventLoop());
            resFuture.complete(actualRes);
        } catch (Throwable t) {
            numActiveRequests.decrementAndGet();
            resFuture.completeExceptionally(t);
        }
    }
}
 
Example 9
Source File: DnsEndpointGroup.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Stops polling DNS servers for service updates.
 */
@Override
protected final void doCloseAsync(CompletableFuture<?> future) {
    final ScheduledFuture<?> scheduledFuture = this.scheduledFuture;
    if (scheduledFuture != null) {
        scheduledFuture.cancel(true);
    }
    future.complete(null);
}
 
Example 10
Source File: EurekaEndpointGroup.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void doCloseAsync(CompletableFuture<?> future) {
    closed = true;
    final ScheduledFuture<?> scheduledFuture = this.scheduledFuture;
    if (scheduledFuture != null) {
        scheduledFuture.cancel(true);
    }
    super.doCloseAsync(future);
}
 
Example 11
Source File: DefaultDnsCache.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
void cancelExpiration() {
    ScheduledFuture<?> expirationFuture = this.expirationFuture;
    if (expirationFuture != null) {
        expirationFuture.cancel(false);
    }
}
 
Example 12
Source File: AbstractNettyIoExecutor.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
@Override
public Cancellable schedule(final Runnable task, final long delay, final TimeUnit unit)
        throws RejectedExecutionException {
    ScheduledFuture<?> future = eventLoop.schedule(task, delay, unit);
    return () -> future.cancel(interruptOnCancel);
}
 
Example 13
Source File: NettyClientMessageHandler.java    From Lottor with MIT License 4 votes vote down vote up
/**
 * 向TxManager 发消息
 *
 * @param lottorRequest 定义的数据传输对象
 * @return Object
 */
public Object sendTxManagerMessage(LottorRequest lottorRequest) {
    if (ctx != null && ctx.channel() != null && ctx.channel().isActive()) {
        final String sendKey = IdWorkerUtils.getInstance().createTaskKey();
        BlockTask sendTask = BlockTaskHelper.getInstance().getTask(sendKey);
        lottorRequest.setKey(sendKey);
        ctx.writeAndFlush(lottorRequest);
        final ScheduledFuture<?> schedule = ctx.executor()
                .schedule(() -> {
                    if (!sendTask.isNotify()) {
                        if (NettyMessageActionEnum.GET_TRANSACTION_GROUP_STATUS.getCode()
                                == lottorRequest.getAction()) {
                            sendTask.setAsyncCall(objects -> NettyResultEnum.TIME_OUT.getCode());
                        } else if (NettyMessageActionEnum.FIND_TRANSACTION_GROUP_INFO.getCode() == lottorRequest.getAction()) {
                            sendTask.setAsyncCall(objects -> null);
                        } else {
                            sendTask.setAsyncCall(objects -> false);
                        }
                        sendTask.signal();
                    }
                }, txConfig.getDelayTime(), TimeUnit.SECONDS);
        //发送线程在此等待,等tm是否 正确返回(正确返回唤醒) 返回错误或者无返回通过上面的调度线程唤醒
        sendTask.await();

        //如果已经被唤醒,就不需要去执行调度线程了 ,关闭上面的调度线程池中的任务
        if (!schedule.isDone()) {
            schedule.cancel(false);
        }
        try {
            return sendTask.getAsyncCall().callBack();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        } finally {
            BlockTaskHelper.getInstance().removeByKey(sendKey);
        }

    } else {
        return null;
    }

}
 
Example 14
Source File: NettyClientMessageHandler.java    From Raincat with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * send message to tx manager .
 *
 * @param heartBeat {@linkplain HeartBeat }
 * @return Object
 */
public Object sendTxManagerMessage(final HeartBeat heartBeat) {
    if (ctx != null && ctx.channel() != null && ctx.channel().isActive()) {
        final String sendKey = IdWorkerUtils.getInstance().createTaskKey();
        BlockTask sendTask = BlockTaskHelper.getInstance().getTask(sendKey);
        heartBeat.setKey(sendKey);
        ctx.writeAndFlush(heartBeat);
        final ScheduledFuture<?> schedule =
                ctx.executor().schedule(() -> {
                    if (!sendTask.isNotify()) {
                        if (NettyMessageActionEnum.GET_TRANSACTION_GROUP_STATUS.getCode()
                                == heartBeat.getAction()) {
                            sendTask.setAsyncCall(objects -> NettyResultEnum.TIME_OUT.getCode());
                        } else if (NettyMessageActionEnum.FIND_TRANSACTION_GROUP_INFO.getCode()
                                == heartBeat.getAction()) {
                            sendTask.setAsyncCall(objects -> null);
                        } else {
                            sendTask.setAsyncCall(objects -> false);
                        }
                        sendTask.signal();
                    }
                }, txConfig.getDelayTime(), TimeUnit.SECONDS);
        //发送线程在此等待,等tm是否 正确返回(正确返回唤醒) 返回错误或者无返回通过上面的调度线程唤醒
        sendTask.await();
        //如果已经被唤醒,就不需要去执行调度线程了 ,关闭上面的调度线程池中的任务
        if (!schedule.isDone()) {
            schedule.cancel(false);
        }
        try {
            return sendTask.getAsyncCall().callBack();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        } finally {
            BlockTaskHelper.getInstance().removeByKey(sendKey);
        }
    } else {
        return null;
    }

}