Example usage for io.netty.util Timeout cancel

List of usage examples for io.netty.util Timeout cancel

Introduction

In this page you can find the example usage for io.netty.util Timeout cancel.

Prototype

boolean cancel();

Source Link

Document

Attempts to cancel the TimerTask associated with this handle.

Usage

From source file:org.apache.hadoop.hbase.client.AsyncRegionLocator.java

License:Apache License

private CompletableFuture<HRegionLocation> withTimeout(CompletableFuture<HRegionLocation> future,
        long timeoutNs, Supplier<String> timeoutMsg) {
    if (future.isDone() || timeoutNs <= 0) {
        return future;
    }//from   w  w  w.j a  va  2  s.co m
    Timeout timeoutTask = retryTimer.newTimeout(t -> {
        if (future.isDone()) {
            return;
        }
        future.completeExceptionally(new TimeoutIOException(timeoutMsg.get()));
    }, timeoutNs, TimeUnit.NANOSECONDS);
    return future.whenComplete((loc, error) -> {
        if (error != null && error.getClass() != TimeoutIOException.class) {
            // cancel timeout task if we are not completed by it.
            timeoutTask.cancel();
        }
    });
}

From source file:org.apache.pulsar.client.impl.ConsumerImpl.java

License:Apache License

@Override
public CompletableFuture<Void> closeAsync() {
    if (getState() == State.Closing || getState() == State.Closed) {
        batchMessageAckTracker.clear();//from  w ww .j  a v a 2 s .co  m
        unAckedMessageTracker.close();
        return CompletableFuture.completedFuture(null);
    }

    if (!isConnected()) {
        log.info("[{}] [{}] Closed Consumer (not connected)", topic, subscription);
        setState(State.Closed);
        batchMessageAckTracker.clear();
        unAckedMessageTracker.close();
        client.cleanupConsumer(this);
        return CompletableFuture.completedFuture(null);
    }

    Timeout timeout = stats.getStatTimeout();
    if (timeout != null) {
        timeout.cancel();
    }

    setState(State.Closing);

    long requestId = client.newRequestId();
    ByteBuf cmd = Commands.newCloseConsumer(consumerId, requestId);

    CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    ClientCnx cnx = cnx();
    cnx.sendRequestWithId(cmd, requestId).handle((v, exception) -> {
        cnx.removeConsumer(consumerId);
        if (exception == null || !cnx.ctx().channel().isActive()) {
            log.info("[{}] [{}] Closed consumer", topic, subscription);
            setState(State.Closed);
            batchMessageAckTracker.clear();
            unAckedMessageTracker.close();
            closeFuture.complete(null);
            client.cleanupConsumer(this);
        } else {
            closeFuture.completeExceptionally(exception);
        }
        return null;
    });

    return closeFuture;
}

From source file:org.apache.pulsar.client.impl.PatternMultiTopicsConsumerImpl.java

License:Apache License

@Override
public CompletableFuture<Void> closeAsync() {
    Timeout timeout = recheckPatternTimeout;
    if (timeout != null) {
        timeout.cancel();
        recheckPatternTimeout = null;/*from  w  w  w .j av a 2s. co  m*/
    }
    return super.closeAsync();
}

From source file:org.apache.pulsar.client.impl.ProducerImpl.java

License:Apache License

@Override
public CompletableFuture<Void> closeAsync() {
    final State currentState = getAndUpdateState(state -> {
        if (state == State.Closed) {
            return state;
        }//from  w ww .  j a  v a 2  s  .c  om
        return State.Closing;
    });

    if (currentState == State.Closed || currentState == State.Closing) {
        return CompletableFuture.completedFuture(null);
    }

    Timeout timeout = sendTimeout;
    if (timeout != null) {
        timeout.cancel();
        sendTimeout = null;
    }

    stats.cancelStatsTimeout();

    ClientCnx cnx = cnx();
    if (cnx == null || currentState != State.Ready) {
        log.info("[{}] [{}] Closed Producer (not connected)", topic, producerName);
        synchronized (this) {
            setState(State.Closed);
            client.cleanupProducer(this);
            PulsarClientException ex = new PulsarClientException.AlreadyClosedException(
                    "Producer was already closed");
            pendingMessages.forEach(msg -> {
                msg.callback.sendComplete(ex);
                msg.cmd.release();
                msg.recycle();
            });
            pendingMessages.clear();
        }

        return CompletableFuture.completedFuture(null);
    }

    long requestId = client.newRequestId();
    ByteBuf cmd = Commands.newCloseProducer(producerId, requestId);

    CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    cnx.sendRequestWithId(cmd, requestId).handle((v, exception) -> {
        cnx.removeProducer(producerId);
        if (exception == null || !cnx.ctx().channel().isActive()) {
            // Either we've received the success response for the close producer command from the broker, or the
            // connection did break in the meantime. In any case, the producer is gone.
            synchronized (ProducerImpl.this) {
                log.info("[{}] [{}] Closed Producer", topic, producerName);
                setState(State.Closed);
                pendingMessages.forEach(msg -> {
                    msg.cmd.release();
                    msg.recycle();
                });
                pendingMessages.clear();
            }

            closeFuture.complete(null);
            client.cleanupProducer(this);
        } else {
            closeFuture.completeExceptionally(exception);
        }

        return null;
    });

    return closeFuture;
}

From source file:org.eclipse.milo.opcua.stack.client.transport.AbstractTransport.java

License:Open Source License

private void cancelRequestTimeout(UaTransportRequest transportRequest) {
    Timeout timeout = transportRequest.getTimeout();
    if (timeout != null)
        timeout.cancel();
}

From source file:org.eclipse.milo.opcua.stack.client.UaTcpStackClient.java

License:Open Source License

private void receiveResponse(UaResponseMessage response) {
    ResponseHeader header = response.getResponseHeader();
    UInteger requestHandle = header.getRequestHandle();

    CompletableFuture<UaResponseMessage> future = pending.remove(requestHandle);

    if (future != null) {
        if (header.getServiceResult().isGood()) {
            future.complete(response);/*from w  w  w  .ja va 2 s.  c  om*/
        } else {
            ServiceFault serviceFault;

            if (response instanceof ServiceFault) {
                serviceFault = (ServiceFault) response;
            } else {
                serviceFault = new ServiceFault(header);
            }

            future.completeExceptionally(new UaServiceFaultException(serviceFault));
        }

        Timeout timeout = timeouts.remove(requestHandle);
        if (timeout != null)
            timeout.cancel();
    } else {
        logger.warn("Received {} for unknown requestHandle: {}", response.getClass().getSimpleName(),
                requestHandle);
    }
}

From source file:org.opendaylight.netvirt.ipv6service.utils.Ipv6TimerWheel.java

License:Open Source License

public void cancelPeriodicTransmissionTimeout(Timeout timeout) {
    if (timeout != null) {
        synchronized (timeout) {
            if (!timeout.isExpired()) {
                timeout.cancel();
            }/*from   www .  ja va2s.  c o m*/
        }
    }
}

From source file:org.opendaylight.sfc.pot.netconf.renderer.provider.SfcPotTimerWheel.java

License:Open Source License

public void clearTimerContext(Timeout timeout) {
    if (timeout != null) {
        synchronized (sfcPotTimerWheelObj) {
            if (!timeout.isExpired()) {
                timeout.cancel();
            }//w w w . j a va  2  s  .co  m
        }
    }
}

From source file:org.redisson.command.CommandAsyncService.java

License:Apache License

private <R, V> void handleBlockingOperations(final AsyncDetails<V, R> details, final RedisConnection connection,
        Long popTimeout) {//from  ww  w .  j  a v a 2s  .  c  o m
    final FutureListener<Boolean> listener = new FutureListener<Boolean>() {
        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            details.getMainPromise().tryFailure(new RedissonShutdownException("Redisson is shutdown"));
        }
    };

    final AtomicBoolean canceledByScheduler = new AtomicBoolean();
    final Timeout scheduledFuture;
    if (popTimeout != 0) {
        // to handle cases when connection has been lost
        final Channel orignalChannel = connection.getChannel();
        scheduledFuture = connectionManager.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                // re-connection wasn't made
                // and connection is still active
                if (orignalChannel == connection.getChannel() && connection.isActive()) {
                    return;
                }

                canceledByScheduler.set(true);
                details.getAttemptPromise().trySuccess(null);
            }
        }, popTimeout, TimeUnit.SECONDS);
    } else {
        scheduledFuture = null;
    }

    details.getMainPromise().addListener(new FutureListener<R>() {
        @Override
        public void operationComplete(Future<R> future) throws Exception {
            if (scheduledFuture != null) {
                scheduledFuture.cancel();
            }

            synchronized (listener) {
                connectionManager.getShutdownPromise().removeListener(listener);
            }

            // handling cancel operation for commands from skipTimeout collection
            if ((future.isCancelled() && details.getAttemptPromise().cancel(true))
                    || canceledByScheduler.get()) {
                connection.forceFastReconnectAsync();
                return;
            }

            if (future.cause() instanceof RedissonShutdownException) {
                details.getAttemptPromise().tryFailure(future.cause());
            }
        }
    });

    synchronized (listener) {
        if (!details.getMainPromise().isDone()) {
            connectionManager.getShutdownPromise().addListener(listener);
        }
    }
}

From source file:org.redisson.command.RedisExecutor.java

License:Apache License

private void checkWriteFuture(ChannelFuture future, RPromise<R> attemptPromise, RedisConnection connection) {
    if (future.isCancelled() || attemptPromise.isDone()) {
        return;/*  ww  w . j a  va  2  s.c  om*/
    }

    if (!future.isSuccess()) {
        exception = new WriteRedisConnectionException(
                "Unable to send command! Node source: " + source + ", connection: " + connection + ", command: "
                        + LogHelper.toString(command, params) + " after " + attempt + " retry attempts",
                future.cause());
        if (attempt == attempts) {
            if (!attemptPromise.tryFailure(exception)) {
                log.error(exception.getMessage());
            }
        }
        return;
    }

    timeout.cancel();

    long timeoutTime = responseTimeout;
    if (command != null && (RedisCommands.BLOCKING_COMMAND_NAMES.contains(command.getName())
            || RedisCommands.BLOCKING_COMMANDS.contains(command))) {
        Long popTimeout = null;
        if (RedisCommands.BLOCKING_COMMANDS.contains(command)) {
            boolean found = false;
            for (Object param : params) {
                if (found) {
                    popTimeout = Long.valueOf(param.toString()) / 1000;
                    break;
                }
                if ("BLOCK".equals(param)) {
                    found = true;
                }
            }
        } else {
            popTimeout = Long.valueOf(params[params.length - 1].toString());
        }

        handleBlockingOperations(attemptPromise, connection, popTimeout);
        if (popTimeout == 0) {
            return;
        }
        timeoutTime += popTimeout * 1000;
        // add 1 second due to issue https://github.com/antirez/redis/issues/874
        timeoutTime += 1000;
    }

    long timeoutAmount = timeoutTime;
    TimerTask timeoutTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (attempt < attempts) {
                if (!attemptPromise.cancel(false)) {
                    return;
                }

                attempt++;
                if (log.isDebugEnabled()) {
                    log.debug("attempt {} for command {} and params {}", attempt, command,
                            LogHelper.toString(params));
                }

                mainPromiseListener = null;

                execute();
                return;
            }

            attemptPromise.tryFailure(new RedisResponseTimeoutException("Redis server response timeout ("
                    + timeoutAmount + " ms) occured" + " after " + attempts + " retry attempts. Command: "
                    + LogHelper.toString(command, params) + ", channel: " + connection.getChannel()));
        }
    };

    timeout = connectionManager.newTimeout(timeoutTask, timeoutTime, TimeUnit.MILLISECONDS);
}