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

The following examples show how to use io.netty.util.Timeout#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: CipClient.java    From ethernet-ip with Apache License 2.0 6 votes vote down vote up
@Override
public void itemsReceived(CpfItem[] items) {
    int connectionId = ((ConnectedAddressItem) items[0]).getConnectionId();
    ByteBuf buffer = ((ConnectedDataItemResponse) items[1]).getData();

    int sequenceNumber = buffer.readShort();
    ByteBuf data = buffer.readSlice(buffer.readableBytes()).retain();

    Timeout timeout = timeouts.remove(sequenceNumber);
    if (timeout != null) timeout.cancel();

    CompletableFuture<ByteBuf> future = pending.remove(sequenceNumber);

    if (future != null) {
        future.complete(data);
    } else {
        ReferenceCountUtil.release(data);
    }

    ReferenceCountUtil.release(buffer);
}
 
Example 2
Source File: RedissonLock.java    From redisson with Apache License 2.0 6 votes vote down vote up
void cancelExpirationRenewal(Long threadId) {
    ExpirationEntry task = EXPIRATION_RENEWAL_MAP.get(getEntryName());
    if (task == null) {
        return;
    }
    
    if (threadId != null) {
        task.removeThreadId(threadId);
    }

    if (threadId == null || task.hasNoThreads()) {
        Timeout timeout = task.getTimeout();
        if (timeout != null) {
            timeout.cancel();
        }
        EXPIRATION_RENEWAL_MAP.remove(getEntryName());
    }
}
 
Example 3
Source File: MetadataClientMock.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private void scheduleNextRetry(GeneratedMessageV3 request, int remainingRetryCount) {
    final TimerTask timerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (timeout.cancel()) {
                return;
            }
            logger.info("Retry {} {}", remainingRetryCount, request);
            request(request, remainingRetryCount - 1);
        }
    };

    try {
        retryTimer.newTimeout(timerTask, 1000, TimeUnit.MILLISECONDS);
    } catch (RejectedExecutionException e) {
        logger.debug("retry fail {}", e.getCause(), e);
    }
}
 
Example 4
Source File: HeartbeatManager.java    From qmq with Apache License 2.0 5 votes vote down vote up
public void refreshHeartbeat(T key, TimerTask task, long timeout, TimeUnit unit) {
    Timeout context = timer.newTimeout(task, timeout, unit);
    final Timeout old = timeouts.put(key, context);
    if (old != null && !old.isCancelled() && !old.isExpired()) {
        old.cancel();
    }
}
 
Example 5
Source File: TimerWheelTimeoutService.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Override
public PingTxnStatus pingTxn(final String scope, final String stream, final UUID txnId, Version version, long lease) {

    if (!this.isRunning()) {
        return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.DISCONNECTED).build();
    }

    final String key = getKey(scope, stream, txnId);
    Preconditions.checkState(map.containsKey(key), "Stream not found in the map");

    final TxnData txnData = map.get(key);

    if (txnData == null) {
        throw new IllegalStateException(String.format("Transaction %s not added to timerWheelTimeoutService", txnId));
    }

    if (lease > maxLeaseValue) {
        return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.LEASE_TOO_LARGE).build();
    }

    if (lease + System.currentTimeMillis() > txnData.getMaxExecutionTimeExpiry()) {
        return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.MAX_EXECUTION_TIME_EXCEEDED).build();
    } else {
        Timeout timeout = txnData.getTimeout();
        boolean cancelSucceeded = timeout.cancel();
        if (cancelSucceeded) {
            TxnData newTxnData = txnData.updateLease(scope, stream, txnId, version, lease);
            map.replace(key, txnData, newTxnData);
            return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.OK).build();
        } else {
            // Cancellation may fail because timeout task (1) may be scheduled for execution, or (2) is executing.
            throw new IllegalStateException(String.format("Failed updating timeout for transaction %s", txnId));
        }
    }

}
 
Example 6
Source File: PatternMultiTopicsConsumerImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> closeAsync() {
    Timeout timeout = recheckPatternTimeout;
    if (timeout != null) {
        timeout.cancel();
        recheckPatternTimeout = null;
    }
    return super.closeAsync();
}
 
Example 7
Source File: UaTcpStackClient.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
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);
        } 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);
    }
}
 
Example 8
Source File: UaTcpStackServer.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
public void secureChannelIssuedOrRenewed(ServerSecureChannel secureChannel, long lifetimeMillis) {
    long channelId = secureChannel.getChannelId();

    /*
     * Cancel any existing timeouts and start a new one.
     */
    Timeout timeout = timeouts.remove(channelId);
    boolean cancelled = (timeout == null || timeout.cancel());

    if (cancelled) {
        timeout = wheelTimer.newTimeout(t ->
                closeSecureChannel(secureChannel), lifetimeMillis, TimeUnit.MILLISECONDS);

        timeouts.put(channelId, timeout);

        /*
         * If this is a reconnect there might be responses queued, so drain those.
         */
        Channel channel = secureChannel.attr(BoundChannelKey).get();

        if (channel != null) {
            List<ServiceResponse> responses = responseQueues.removeAll(channelId);

            responses.forEach(channel::write);
            channel.flush();
        }
    }
}
 
Example 9
Source File: MetadataGrpcDataSender.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private void scheduleNextRetry(final GeneratedMessageV3 message, final int remainingRetryCount) {
    if (shutdown) {
        if (isDebug) {
            logger.debug("Request drop. Already shutdown request={}", MessageFormatUtils.debugLog(message));
        }
        return;
    }
    if (remainingRetryCount <= 0) {
        if (isDebug) {
            logger.debug("Request drop. remainingRetryCount={}, request={}", MessageFormatUtils.debugLog(message), remainingRetryCount);
        }
        return;
    }

    if (isDebug) {
        logger.debug("Request retry. request={}, remainingRetryCount={}", MessageFormatUtils.debugLog(message), remainingRetryCount);
    }
    final TimerTask timerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (timeout.cancel()) {
                return;
            }
            if (shutdown) {
                return;
            }
            request0(message, remainingRetryCount);
        }
    };

    try {
        retryTimer.newTimeout(timerTask, retryDelayMillis, TimeUnit.MILLISECONDS);
    } catch (RejectedExecutionException e) {
        logger.debug("retry fail {}", e.getCause(), e);
    }
}
 
Example 10
Source File: CommunicationClient.java    From brpc-java with Apache License 2.0 4 votes vote down vote up
public void execute(Request request, Response response) throws RpcException {
    request.setCommunicationClient(this);
    Channel channel = selectChannel();
    request.setChannel(channel);
    ChannelInfo channelInfo = ChannelInfo.getClientChannelInfo(channel);
    RpcFuture rpcFuture = RpcFuture.createRpcFuture(request);
    if (request.getCallback() != null) {
        rpcFuture.setInterceptors(interceptors);
    }
    channelInfo.setCorrelationId(rpcFuture.getCorrelationId());
    rpcFuture.setChannelInfo(channelInfo);
    rpcFuture.setChannelType(communicationOptions.getChannelType());
    request.setRpcFuture(rpcFuture);
    request.setCorrelationId(rpcFuture.getCorrelationId());

    try {
        request.setSendBuf(communicationOptions.getProtocol().encodeRequest(request));
    } catch (Throwable t) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, t.getMessage(), t);
    }

    // register timeout timer
    Timer timeoutTimer = TimerInstance.getInstance();
    RpcTimeoutTimer timeoutTask = new RpcTimeoutTimer(
            channelInfo, request.getCorrelationId(), communicationOptions.getProtocol());
    Timeout timeout = timeoutTimer.newTimeout(timeoutTask, request.getReadTimeoutMillis(), TimeUnit.MILLISECONDS);
    request.getRpcFuture().setTimeout(timeout);
    try {
        // netty will release the send buffer after sent.
        // we retain here, so it can be used when rpc retry.
        request.retain();
        ChannelFuture sendFuture = request.getChannel().writeAndFlush(request.getSendBuf());
        sendFuture.awaitUninterruptibly(request.getWriteTimeoutMillis());
        if (!sendFuture.isSuccess()) {
            if (!(sendFuture.cause() instanceof ClosedChannelException)) {
                log.warn("send request failed, channelActive={}, ex=",
                        request.getChannel().isActive(), sendFuture.cause());
            }
            String errMsg = String.format("send request failed, channelActive=%b",
                    request.getChannel().isActive());
            throw new RpcException(RpcException.NETWORK_EXCEPTION, errMsg);
        }
    } catch (Exception ex) {
        channelInfo.handleRequestFail(communicationOptions.getChannelType(), request.getCorrelationId());
        timeout.cancel();
        log.debug("send request failed:", ex);
        if (ex instanceof RpcException) {
            throw (RpcException) ex;
        } else {
            throw new RpcException(RpcException.NETWORK_EXCEPTION, "send request failed", ex);
        }
    }

    // return channel
    channelInfo.handleRequestSuccess(communicationOptions.getChannelType());

    // receive
    if (rpcFuture.isAsync()) {
        response.setRpcFuture(rpcFuture);
    } else {
        response.setResult(rpcFuture.get(request.getReadTimeoutMillis(), TimeUnit.MILLISECONDS));
        response.setCorrelationId(rpcFuture.getCorrelationId());
    }
}
 
Example 11
Source File: HeartbeatManager.java    From qmq with Apache License 2.0 4 votes vote down vote up
public void cancel(T key) {
    Timeout timeout = timeouts.remove(key);
    if (timeout == null) return;

    timeout.cancel();
}