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

The following examples show how to use io.netty.util.Timeout#isCancelled() . 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: ReadRequestTimeoutTimerTask.java    From async-gamequery-lib with MIT License 6 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    log.debug("Timeout occured for Session {}", id);
    //Notify the listener that timeout has occured
    final SessionValue session = sessionManager.getSession(id);

    //Do not proceed if the session is null
    if (session == null) {
        log.error("could not find session value for id {}. Registry Size : {}", id, sessionManager.getSessionEntries().size());
        return;
    }

    //Check first if the promise has been completed
    if (session.getClientPromise() != null && !session.getClientPromise().isDone() && !session.getClientPromise().isCancelled() && !timeout.isCancelled()) {
        //Send a ReadTimeoutException to the client
        session.getClientPromise().completeExceptionally(new ReadTimeoutException(id, String.format("Timeout occured for '%s' Started: %f seconds ago", id, ((double) Duration.ofMillis(System.currentTimeMillis() - session.getTimeRegistered()).toMillis() / 1000.0))));
    }
}
 
Example 2
Source File: MultiTopicsConsumerImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled() || getState() != State.Ready) {
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("[{}] run partitionsAutoUpdateTimerTask", topic);
    }

    // if last auto update not completed yet, do nothing.
    if (partitionsAutoUpdateFuture == null || partitionsAutoUpdateFuture.isDone()) {
        partitionsAutoUpdateFuture = topicsPartitionChangedListener.onTopicsExtended(topics.keySet());
    }

    // schedule the next re-check task
    partitionsAutoUpdateTimeout = client.timer()
        .newTimeout(partitionsAutoUpdateTimerTask, 1, TimeUnit.MINUTES);
}
 
Example 3
Source File: ProducerImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }
    if (log.isTraceEnabled()) {
        log.trace("[{}] [{}] Batching the messages from the batch container from timer thread", topic,
                producerName);
    }
    // semaphore acquired when message was enqueued to container
    synchronized (ProducerImpl.this) {
        // If it's closing/closed we need to ignore the send batch timer and not schedule next timeout.
        if (getState() == State.Closing || getState() == State.Closed) {
            return;
        }

        batchMessageAndSend();
        // schedule the next batch message task
        batchMessageAndSendTimeout = client.timer()
            .newTimeout(this, conf.getBatchingMaxPublishDelayMicros(), TimeUnit.MICROSECONDS);
    }
}
 
Example 4
Source File: PartitionedProducerImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled() || getState() != State.Ready) {
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("[{}] run partitionsAutoUpdateTimerTask for partitioned producer", topic);
    }

    // if last auto update not completed yet, do nothing.
    if (partitionsAutoUpdateFuture == null || partitionsAutoUpdateFuture.isDone()) {
        partitionsAutoUpdateFuture = topicsPartitionChangedListener.onTopicsExtended(ImmutableList.of(topic));
    }

    // schedule the next re-check task
    partitionsAutoUpdateTimeout = client.timer()
        .newTimeout(partitionsAutoUpdateTimerTask, 1, TimeUnit.MINUTES);
}
 
Example 5
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 6
Source File: InMemoryDelayedDeliveryTracker.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("[{}] Timer triggered", dispatcher.getName());
    }
    if (timeout.isCancelled()) {
        return;
    }

    synchronized (dispatcher) {
        currentTimeoutTarget = -1;
        timeout = null;
        dispatcher.readMoreEntries();
    }
}
 
Example 7
Source File: PatternMultiTopicsConsumerImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    CompletableFuture<Void> recheckFuture = new CompletableFuture<>();
    List<CompletableFuture<Void>> futures = Lists.newArrayListWithExpectedSize(2);

    client.getLookup().getTopicsUnderNamespace(namespaceName, subscriptionMode).thenAccept(topics -> {
        if (log.isDebugEnabled()) {
            log.debug("Get topics under namespace {}, topics.size: {}", namespaceName.toString(), topics.size());
            topics.forEach(topicName ->
                log.debug("Get topics under namespace {}, topic: {}", namespaceName.toString(), topicName));
        }

        List<String> newTopics = PulsarClientImpl.topicsPatternFilter(topics, topicsPattern);
        List<String> oldTopics = PatternMultiTopicsConsumerImpl.this.getTopics();

        futures.add(topicsChangeListener.onTopicsAdded(topicsListsMinus(newTopics, oldTopics)));
        futures.add(topicsChangeListener.onTopicsRemoved(topicsListsMinus(oldTopics, newTopics)));
        FutureUtil.waitForAll(futures)
            .thenAccept(finalFuture -> recheckFuture.complete(null))
            .exceptionally(ex -> {
                log.warn("[{}] Failed to recheck topics change: {}", topic, ex.getMessage());
                recheckFuture.completeExceptionally(ex);
                return null;
            });
    });

    // schedule the next re-check task
    this.recheckPatternTimeout = client.timer().newTimeout(PatternMultiTopicsConsumerImpl.this,
            Math.max(1, conf.getPatternAutoDiscoveryPeriod()), TimeUnit.SECONDS);
}
 
Example 8
Source File: ConsumerBase.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private void pendingBatchReceiveTask(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    long timeToWaitMs;

    synchronized (this) {
        // If it's closing/closed we need to ignore this timeout and not schedule next timeout.
        if (getState() == State.Closing || getState() == State.Closed) {
            return;
        }
        if (pendingBatchReceives == null) {
            pendingBatchReceives = Queues.newConcurrentLinkedQueue();
        }
        OpBatchReceive<T> firstOpBatchReceive = pendingBatchReceives.peek();
        timeToWaitMs = batchReceivePolicy.getTimeoutMs();

        while (firstOpBatchReceive != null) {
            // If there is at least one batch receive, calculate the diff between the batch receive timeout
            // and the elapsed time since the operation was created.
            long diff = batchReceivePolicy.getTimeoutMs()
                    - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - firstOpBatchReceive.createdAt);
            if (diff <= 0) {
                // The diff is less than or equal to zero, meaning that the batch receive has been timed out.
                // complete the OpBatchReceive and continue to check the next OpBatchReceive in pendingBatchReceives.
                OpBatchReceive<T> op = pendingBatchReceives.poll();
                completeOpBatchReceive(op);
                firstOpBatchReceive = pendingBatchReceives.peek();
            } else {
                // The diff is greater than zero, set the timeout to the diff value
                timeToWaitMs = diff;
                break;
            }
        }
        batchReceiveTimeout = client.timer().newTimeout(this::pendingBatchReceiveTask, timeToWaitMs, TimeUnit.MILLISECONDS);
    }
}
 
Example 9
Source File: IdleStateChecker.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled() || !ctx.channel().isOpen()) {
        return;
    }

    long lastReadTime = IdleStateChecker.this.lastReadTime;
    long nextDelay = readerIdleTimeMillis;
    if (!reading) {
        nextDelay -= SystemClock.millisClock().now() - lastReadTime;
    }
    if (nextDelay <= 0) {
        // Reader is idle - set a new timeout and notify the callback.
        readerIdleTimeout = timer.newTimeout(this, readerIdleTimeMillis, TimeUnit.MILLISECONDS);
        try {
            IdleStateEvent event;
            if (firstReaderIdleEvent) {
                firstReaderIdleEvent = false;
                event = IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT;
            } else {
                event = IdleStateEvent.READER_IDLE_STATE_EVENT;
            }
            channelIdle(ctx, event);
        } catch (Throwable t) {
            ctx.fireExceptionCaught(t);
        }
    } else {
        // Read occurred before the timeout - set a new timeout with shorter delay.
        readerIdleTimeout = timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS);
    }
}
 
Example 10
Source File: IdleStateChecker.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled() || !ctx.channel().isOpen()) {
        return;
    }

    long lastWriteTime = IdleStateChecker.this.lastWriteTime;
    long nextDelay = writerIdleTimeMillis - (SystemClock.millisClock().now() - lastWriteTime);
    if (nextDelay <= 0) {
        // Writer is idle - set a new timeout and notify the callback.
        writerIdleTimeout = timer.newTimeout(this, writerIdleTimeMillis, TimeUnit.MILLISECONDS);
        try {
            IdleStateEvent event;
            if (firstWriterIdleEvent) {
                firstWriterIdleEvent = false;
                event = IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT;
            } else {
                event = IdleStateEvent.WRITER_IDLE_STATE_EVENT;
            }
            channelIdle(ctx, event);
        } catch (Throwable t) {
            ctx.fireExceptionCaught(t);
        }
    } else {
        // Write occurred before the timeout - set a new timeout with shorter delay.
        writerIdleTimeout = timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS);
    }
}
 
Example 11
Source File: IdleStateChecker.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled() || !ctx.channel().isOpen()) {
        return;
    }

    long nextDelay = allIdleTimeMillis;
    if (!reading) {
        long lastIoTime = Math.max(lastReadTime, lastWriteTime);
        nextDelay -= SystemClock.millisClock().now() - lastIoTime;
    }
    if (nextDelay <= 0) {
        // Both reader and writer are idle - set a new timeout and
        // notify the callback.
        allIdleTimeout = timer.newTimeout(this, allIdleTimeMillis, TimeUnit.MILLISECONDS);
        try {
            IdleStateEvent event;
            if (firstAllIdleEvent) {
                firstAllIdleEvent = false;
                event = IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT;
            } else {
                event = IdleStateEvent.ALL_IDLE_STATE_EVENT;
            }
            channelIdle(ctx, event);
        } catch (Throwable t) {
            ctx.fireExceptionCaught(t);
        }
    } else {
        // Either read or write occurred before the timeout - set a new
        // timeout with shorter delay.
        allIdleTimeout = timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS);
    }
}
 
Example 12
Source File: NullPacketProvider.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Timeout to) {
    if (!devices.isEmpty() && !to.isCancelled() && delay > 0) {
        sendEvent(devices.get(Math.min(currentDevice, devices.size() - 1)));
        currentDevice = (currentDevice + 1) % devices.size();
        timeout = to.timer().newTimeout(to.task(), delay, TimeUnit.MILLISECONDS);
    }
}
 
Example 13
Source File: TunnelStatsCollector.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (stopped || timeout.isCancelled()) {
        return;
    }
    log.trace("Collecting stats for {}", pcepTunnelId);

    sendTunnelStatistic();
    if (!stopped && !timeout.isCancelled()) {
        log.trace("Scheduling stats collection in {} seconds for {}",
                  this.refreshInterval, pcepTunnelId);
        timeout.timer().newTimeout(this, refreshInterval, TimeUnit.SECONDS);
    }

}
 
Example 14
Source File: ProducerImpl.java    From pulsar with Apache License 2.0 4 votes vote down vote up
/**
 * Process sendTimeout events
 */
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    long timeToWaitMs;

    synchronized (this) {
        // If it's closing/closed we need to ignore this timeout and not schedule next timeout.
        if (getState() == State.Closing || getState() == State.Closed) {
            return;
        }

        OpSendMsg firstMsg = pendingMessages.peek();
        if (firstMsg == null) {
            // If there are no pending messages, reset the timeout to the configured value.
            timeToWaitMs = conf.getSendTimeoutMs();
        } else {
            // If there is at least one message, calculate the diff between the message timeout and the elapsed
            // time since first message was created.
            long diff = conf.getSendTimeoutMs()
                    - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - firstMsg.createdAt);
            if (diff <= 0) {
                // The diff is less than or equal to zero, meaning that the message has been timed out.
                // Set the callback to timeout on every message, then clear the pending queue.
                log.info("[{}] [{}] Message send timed out. Failing {} messages", topic, producerName,
                        pendingMessages.size());

                PulsarClientException te = new PulsarClientException.TimeoutException(
                    format("The producer %s can not send message to the topic %s within given timeout",
                        producerName, topic), firstMsg.sequenceId);
                failPendingMessages(cnx(), te);
                stats.incrementSendFailed(pendingMessages.size());
                // Since the pending queue is cleared now, set timer to expire after configured value.
                timeToWaitMs = conf.getSendTimeoutMs();
            } else {
                // The diff is greater than zero, set the timeout to the diff value
                timeToWaitMs = diff;
            }
        }

        sendTimeout = client.timer().newTimeout(this, timeToWaitMs, TimeUnit.MILLISECONDS);
    }
}
 
Example 15
Source File: TransactionMetaStoreHandler.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }
    long timeToWaitMs;
    if (getState() == State.Closing || getState() == State.Closed) {
        return;
    }
    RequestTime peeked = timeoutQueue.peek();
    while (peeked != null && peeked.creationTimeMs + client.getConfiguration().getOperationTimeoutMs()
            - System.currentTimeMillis() <= 0) {
        RequestTime lastPolled = timeoutQueue.poll();
        if (lastPolled != null) {
            OpBase<?> op = pendingRequests.remove(lastPolled.requestId);
            if (!op.callback.isDone()) {
                op.callback.completeExceptionally(new PulsarClientException.TimeoutException(
                        "Could not get response from transaction meta store within given timeout."));
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Transaction coordinator request {} is timeout.", lastPolled.requestId);
                }
                onResponse(op);
            }
        } else {
            break;
        }
        peeked = timeoutQueue.peek();
    }

    if (peeked == null) {
        timeToWaitMs = client.getConfiguration().getOperationTimeoutMs();
    } else {
        long diff = (peeked.creationTimeMs + client.getConfiguration().getOperationTimeoutMs()) - System.currentTimeMillis();
        if (diff <= 0) {
            timeToWaitMs = client.getConfiguration().getOperationTimeoutMs();
        } else {
            timeToWaitMs = diff;
        }
    }
    requestTimeout = client.timer().newTimeout(this, timeToWaitMs, TimeUnit.MILLISECONDS);
}