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:TimerTest.java

License:Open Source License

public static void main(String[] args) {

    LacpWheelTimer instance = TimerFactory.LacpWheelTimer.getInstance(Utils.timerWheeltype.WAIT_WHILE_TIMER);
    System.out.println("Starting adding the Ports in wheel at " + getTime() + " and time in ms is "
            + System.currentTimeMillis());
    for (int i = 0; i < 400; i++) {

        PortWaitWhileTimerRegister objPort = new PortWaitWhileTimerRegister((short) i, 1L);

        System.out.println("Inserting Port " + i + " at " + System.currentTimeMillis());

        Timeout obj = null;
        obj = instance.registerPortForWaitWhileTimer(objPort, 5, TimeUnit.SECONDS);

        if (i == 3) {
            obj.cancel();
            try {
                Thread.sleep(000);
                obj.cancel();//from  w ww  . ja v  a  2 s.  c  o  m
            } catch (InterruptedException ex) {

            }
        }

    }

}

From source file:com.corundumstudio.socketio.scheduler.HashedWheelScheduler.java

License:Apache License

public void cancel(SchedulerKey key) {
    Timeout timeout = scheduledFutures.remove(key);
    if (timeout != null) {
        timeout.cancel();
    }
}

From source file:com.corundumstudio.socketio.scheduler.HashedWheelTimeoutScheduler.java

License:Apache License

private void replaceScheduledFuture(final SchedulerKey key, final Timeout newTimeout) {
    final Timeout oldTimeout;

    if (newTimeout.isExpired()) {
        // no need to put already expired timeout to scheduledFutures map.
        // simply remove old timeout
        oldTimeout = scheduledFutures.remove(key);
    } else {/* w  ww  . j  a  va2  s  . c o m*/
        oldTimeout = scheduledFutures.put(key, newTimeout);
    }

    // if there was old timeout, cancel it
    if (oldTimeout != null) {
        oldTimeout.cancel();
    }
}

From source file:com.digitalpetri.opcua.stack.client.UaTcpStackClient.java

License:Apache 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);/*  w w w .  j  a v  a2s  .  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.debug("Received {} for unknown requestHandle: {}", response.getClass().getSimpleName(),
                requestHandle);
    }
}

From source file:com.digitalpetri.opcua.stack.server.tcp.UaTcpStackServer.java

License:Apache License

public void secureChannelIssuedOrRenewed(ServerSecureChannel secureChannel, long lifetimeMillis) {
    long channelId = secureChannel.getChannelId();

    /*// ww  w .  ja v a 2 s  .  c om
     * 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();
        }
    }
}

From source file:com.heliosapm.streams.collector.jmx.JMXClient.java

License:Apache License

/**
 * Acquires the MBeanServerConnection server
 * @return the MBeanServerConnection server
 *///from  www. ja v  a2s  . co  m
public MBeanServerConnection server() {
    if (server == null) {
        synchronized (this) {
            if (server == null) {
                try {
                    final Thread me = Thread.currentThread();
                    final Timeout txout = TimeoutService.getInstance().timeout(connectTimeoutSecs,
                            TimeUnit.SECONDS, new Runnable() {
                                @Override
                                public void run() {
                                    log.warn("Connect Timeout !!!\n{}", StringHelper.formatStackTrace(me));
                                    me.interrupt();
                                    log.warn("JMXConnector interrupted after timeout");
                                }
                            });
                    //                  if(hystrixEnabled.get()) {
                    //                     commandBuilder.commandFor(new Callable<Object>(){
                    //                        @Override
                    //                        public Void call() throws Exception {
                    //                           jmxConnector.connect();
                    //                           return null;
                    //                        }
                    //                     }).execute();
                    //                  } else {
                    jmxConnector.connect();
                    //                  }

                    //                  server = jmxConnector.getMBeanServerConnection();
                    final MBeanServerConnection conn = jmxConnector.getMBeanServerConnection();
                    try {
                        server = (MBeanServerConnection) Proxy.newProxyInstance(
                                Thread.currentThread().getContextClassLoader(),
                                new Class[] { MBeanServerConnection.class }, new InvocationHandler() {
                                    @Override
                                    public Object invoke(final Object proxy, final Method method,
                                            final Object[] args) throws Throwable {
                                        // FIXME: add a timeout watcher here.
                                        final long start = System.currentTimeMillis();
                                        try {
                                            return method.invoke(conn, args);
                                        } finally {
                                            remotingTime.add(System.currentTimeMillis() - start);
                                        }
                                    }
                                });
                    } catch (Exception ex) {
                        server = conn;
                        log.warn(
                                "Failed to create Instrumented Proxy for JMX MBeanConnection Server [{}]. Continuing with native",
                                this.jmxServiceUrl, ex);
                    }
                    txout.cancel();
                    for (SavedNotificationEvent n : registrations) {
                        try {
                            if (n.listener != null) {
                                server.addNotificationListener(n.name, n.listener, n.filter, n.handback);
                            } else {
                                server.addNotificationListener(n.name, n.listenerObjectName, n.filter,
                                        n.handback);
                            }
                        } catch (Exception ex) {
                            registrations.remove(n);
                            log.error("Failed to apply notif registration [" + n + "]", ex);
                        }
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(
                            "Failed to get MBeanServerConnection for [" + jmxServiceUrl + "]", ex);
                }
            }
        }
    }
    return server;
}

From source file:com.king.platform.net.http.netty.TimeoutTimerHandler.java

License:Apache License

public void scheduleTimeout(final TimeoutTimerTask task, long delayTime, TimeUnit timeUnit) {
    final Timeout timeout = nettyTimer.newTimeout(task, delayTime, timeUnit);

    requestEventBus.subscribe(Event.ERROR, new EventBusCallback2<HttpRequestContext, Throwable>() {
        @Override//from  ww w.j av  a2 s .  co m
        public void onEvent(Event2<HttpRequestContext, Throwable> event, HttpRequestContext payload1,
                Throwable payload2) {
            task.cancel();
            timeout.cancel();
        }
    });

    requestEventBus.subscribe(Event.COMPLETED, new EventBusCallback1<HttpRequestContext>() {
        @Override
        public void onEvent(Event1<HttpRequestContext> event, HttpRequestContext payload) {
            task.completed();
            timeout.cancel();
        }
    });

}

From source file:com.lambdaworks.redis.PlainChannelInitializer.java

License:Apache License

static void pingBeforeActivate(AsyncCommand<?, ?, ?> cmd, CompletableFuture<Boolean> initializedFuture,
        ChannelHandlerContext ctx, ClientResources clientResources, long timeout, TimeUnit timeUnit)
        throws Exception {

    ctx.channel().writeAndFlush(cmd);// w  w w  .j av  a 2  s  .  c o  m

    Runnable timeoutGuard = () -> {

        if (cmd.isDone() || initializedFuture.isDone()) {
            return;
        }

        initializedFuture.completeExceptionally(new RedisCommandTimeoutException(String
                .format("Cannot initialize channel (PING before activate) within %d %s", timeout, timeUnit)));
    };

    Timeout timeoutHandle = clientResources.timer().newTimeout(t -> {

        if (clientResources.eventExecutorGroup().isShuttingDown()) {
            timeoutGuard.run();
            return;
        }

        clientResources.eventExecutorGroup().submit(timeoutGuard);
    }, timeout, timeUnit);

    cmd.whenComplete((o, throwable) -> {

        timeoutHandle.cancel();

        if (throwable == null) {
            ctx.fireChannelActive();
            initializedFuture.complete(true);
        } else {
            initializedFuture.completeExceptionally(throwable);
        }
    });

}

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClient.java

License:Apache License

private <R> ChannelFutureListener handleRequestSent(final ResolvableFuture<R> future,
        final AtomicReference<Timeout> heartbeatTimeout, final Timeout requestTimeout) {
    return new ChannelFutureListener() {
        @Override//from w  w  w . jav a2s.com
        public void operationComplete(ChannelFuture f) throws Exception {
            requestTimeout.cancel();

            if (!f.isSuccess()) {
                future.fail(f.cause());
                return;
            }

            final Timeout timeout = timer.newTimeout(heartbeatTimeout(f.channel(), future), heartbeatInterval,
                    TimeUnit.MILLISECONDS);

            heartbeatTimeout.set(timeout);
        }
    };
}

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClientSession.java

License:Apache License

private void unsetTimeout() {
    final Timeout old = heartbeatTimeout.getAndSet(null);

    if (old != null) {
        old.cancel();
    }//  www .  j  av  a 2 s .c  om
}