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.redisson.command.RedisExecutor.java

License:Apache License

private void handleBlockingOperations(RPromise<R> attemptPromise, RedisConnection connection, Long popTimeout) {
    FutureListener<Void> listener = f -> {
        mainPromise.tryFailure(new RedissonShutdownException("Redisson is shutdown"));
    };/*from   w  ww. j a va2 s.  c om*/

    Timeout scheduledFuture;
    if (popTimeout != 0) {
        // handling cases when connection has been lost
        scheduledFuture = connectionManager.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                if (attemptPromise.trySuccess(null)) {
                    connection.forceFastReconnectAsync();
                }
            }
        }, popTimeout, TimeUnit.SECONDS);
    } else {
        scheduledFuture = null;
    }

    mainPromise.onComplete((res, e) -> {
        if (scheduledFuture != null) {
            scheduledFuture.cancel();
        }

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

        // handling cancel operation for blocking commands
        if (mainPromise.isCancelled() && !attemptPromise.isDone()) {
            log.debug("Canceled blocking operation {} used {}", command, connection);
            connection.forceFastReconnectAsync().onComplete((r, ex) -> {
                attemptPromise.cancel(true);
            });
            return;
        }

        if (e instanceof RedissonShutdownException) {
            attemptPromise.tryFailure(e);
        }
    });

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

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

License:Apache License

protected void checkAttemptPromise(RPromise<R> attemptFuture, RFuture<RedisConnection> connectionFuture) {
    timeout.cancel();
    if (attemptFuture.isCancelled()) {
        return;//from   w w  w.j  av  a2s  . co  m
    }

    try {
        mainPromiseListener = null;

        if (attemptFuture.cause() instanceof RedisMovedException && !ignoreRedirect) {
            RedisMovedException ex = (RedisMovedException) attemptFuture.cause();
            if (source.getRedirect() == Redirect.MOVED) {
                mainPromise.tryFailure(new RedisException("MOVED redirection loop detected. Node "
                        + source.getAddr() + " has further redirect to " + ex.getUrl()));
                return;
            }

            onException();

            source = new NodeSource(ex.getSlot(), connectionManager.applyNatMap(ex.getUrl()), Redirect.MOVED);
            execute();
            return;
        }

        if (attemptFuture.cause() instanceof RedisAskException && !ignoreRedirect) {
            RedisAskException ex = (RedisAskException) attemptFuture.cause();

            onException();

            source = new NodeSource(ex.getSlot(), connectionManager.applyNatMap(ex.getUrl()), Redirect.ASK);
            execute();
            return;
        }

        if (attemptFuture.cause() instanceof RedisLoadingException
                || attemptFuture.cause() instanceof RedisTryAgainException) {
            if (attempt < attempts) {
                onException();
                connectionManager.newTimeout(new TimerTask() {
                    @Override
                    public void run(Timeout timeout) throws Exception {
                        attempt++;
                        execute();
                    }
                }, Math.min(responseTimeout, 1000), TimeUnit.MILLISECONDS);
                return;
            }
        }

        free();

        handleResult(attemptFuture, connectionFuture);

    } catch (Exception e) {
        handleError(connectionFuture, e);
    }
}

From source file:org.redisson.CommandBatchExecutorService.java

License:Apache License

public void execute(final Entry entry, final int slot, final Promise<Void> mainPromise,
        final AtomicInteger slots, final int attempt) {
    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.setFailure(new IllegalStateException("Redisson is shutdown"));
        return;/*from   w ww.j av a  2  s .c  o m*/
    }

    final Promise<Void> attemptPromise = connectionManager.newPromise();
    final AtomicReference<RedisException> ex = new AtomicReference<RedisException>();

    final TimerTask retryTimerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (attemptPromise.isDone()) {
                return;
            }
            if (attempt == connectionManager.getConfig().getRetryAttempts()) {
                attemptPromise.setFailure(ex.get());
                return;
            }
            attemptPromise.cancel(true);

            int count = attempt + 1;
            execute(entry, slot, mainPromise, slots, count);
        }
    };

    try {
        org.redisson.client.RedisConnection connection;
        if (entry.isReadOnlyMode()) {
            connection = connectionManager.connectionReadOp(slot);
        } else {
            connection = connectionManager.connectionWriteOp(slot);
        }

        ArrayList<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(entry.getCommands().size());
        for (CommandEntry c : entry.getCommands()) {
            list.add(c.getCommand());
        }
        ChannelFuture future = connection.send(new CommandsData(attemptPromise, list));

        ex.set(new RedisTimeoutException());
        final Timeout timeout = connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getTimeout(), TimeUnit.MILLISECONDS);

        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    timeout.cancel();
                    ex.set(new WriteRedisConnectionException("channel: " + future.channel() + " closed"));
                    connectionManager.getTimer().newTimeout(retryTimerTask,
                            connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
                }
            }
        });

        if (entry.isReadOnlyMode()) {
            attemptPromise.addListener(connectionManager.createReleaseReadListener(slot, connection, timeout));
        } else {
            attemptPromise.addListener(connectionManager.createReleaseWriteListener(slot, connection, timeout));
        }
    } catch (RedisException e) {
        ex.set(e);
        connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    }
    attemptPromise.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (future.isCancelled()) {
                return;
            }

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                execute(entry, ex.getSlot(), mainPromise, slots, attempt);
                return;
            }

            if (future.isSuccess()) {
                if (slots.decrementAndGet() == 0) {
                    mainPromise.setSuccess(future.getNow());
                }
            } else {
                mainPromise.setFailure(future.cause());
            }
        }
    });
}

From source file:org.redisson.CommandExecutorService.java

License:Apache License

protected <V, R> void async(final boolean readOnlyMode, final int slot,
        final MultiDecoder<Object> messageDecoder, final Codec codec, final RedisCommand<V> command,
        final Object[] params, final Promise<R> mainPromise, final int attempt) {
    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.setFailure(new IllegalStateException("Redisson is shutdown"));
        return;//from  ww  w.  ja  v a2  s . co  m
    }

    final Promise<R> attemptPromise = connectionManager.newPromise();
    final AtomicReference<RedisException> ex = new AtomicReference<RedisException>();

    final TimerTask retryTimerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (attemptPromise.isDone()) {
                return;
            }
            if (attempt == connectionManager.getConfig().getRetryAttempts()) {
                attemptPromise.setFailure(ex.get());
                return;
            }
            if (!attemptPromise.cancel(false)) {
                return;
            }

            int count = attempt + 1;
            async(readOnlyMode, slot, messageDecoder, codec, command, params, mainPromise, count);
        }
    };

    try {
        org.redisson.client.RedisConnection connection;
        if (readOnlyMode) {
            connection = connectionManager.connectionReadOp(slot);
        } else {
            connection = connectionManager.connectionWriteOp(slot);
        }
        log.debug("getting connection for command {} via slot {} using {}", command, slot,
                connection.getRedisClient().getAddr());
        ChannelFuture future = connection
                .send(new CommandData<V, R>(attemptPromise, messageDecoder, codec, command, params));

        ex.set(new RedisTimeoutException());
        final Timeout timeout = connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getTimeout(), TimeUnit.MILLISECONDS);

        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    timeout.cancel();
                    ex.set(new WriteRedisConnectionException("Can't send command: " + command + ", params: "
                            + params + ", channel: " + future.channel(), future.cause()));
                    connectionManager.getTimer().newTimeout(retryTimerTask,
                            connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
                }
            }
        });

        if (readOnlyMode) {
            attemptPromise.addListener(connectionManager.createReleaseReadListener(slot, connection, timeout));
        } else {
            attemptPromise.addListener(connectionManager.createReleaseWriteListener(slot, connection, timeout));
        }
    } catch (RedisException e) {
        ex.set(e);
        connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    }
    attemptPromise.addListener(new FutureListener<R>() {
        @Override
        public void operationComplete(Future<R> future) throws Exception {
            if (future.isCancelled()) {
                return;
            }
            // TODO cancel timeout

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                connectionManager.getTimer().newTimeout(retryTimerTask,
                        connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
                async(readOnlyMode, ex.getSlot(), messageDecoder, codec, command, params, mainPromise, attempt);
                return;
            }

            if (future.isSuccess()) {
                mainPromise.setSuccess(future.getNow());
            } else {
                mainPromise.setFailure(future.cause());
            }
        }
    });
}

From source file:org.redisson.connection.MasterSlaveConnectionManager.java

License:Apache License

public <T> FutureListener<T> createReleaseWriteListener(final int slot, final RedisConnection conn,
        final Timeout timeout) {
    return new FutureListener<T>() {
        @Override//  ww  w  .j  a v a2  s  .  co  m
        public void operationComplete(io.netty.util.concurrent.Future<T> future) throws Exception {
            timeout.cancel();
            releaseWrite(slot, conn);
        }
    };
}

From source file:org.redisson.connection.MasterSlaveConnectionManager.java

License:Apache License

public <T> FutureListener<T> createReleaseReadListener(final int slot, final RedisConnection conn,
        final Timeout timeout) {
    return new FutureListener<T>() {
        @Override//from  www.  j  a  v  a2s.  c  om
        public void operationComplete(io.netty.util.concurrent.Future<T> future) throws Exception {
            timeout.cancel();
            releaseRead(slot, conn);
        }
    };
}

From source file:org.redisson.QueueTransferTask.java

License:Apache License

private void scheduleTask(final Long startTime) {
    if (startTime == null) {
        return;/*ww  w. j a  va 2  s.c o  m*/
    }

    Timeout oldTimeout = timeoutReference.get();
    if (oldTimeout != null) {
        oldTimeout.cancel();
        timeoutReference.compareAndSet(oldTimeout, null);
    }

    long delay = startTime - System.currentTimeMillis();
    if (delay > 10) {
        Timeout timeout = connectionManager.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                pushTask();
            }
        }, delay, TimeUnit.MILLISECONDS);
        timeoutReference.set(timeout);
    } else {
        pushTask();
    }
}

From source file:org.redisson.RedissonPermitExpirableSemaphore.java

License:Apache License

private void tryAcquireAsync(final AtomicLong time, final int permits,
        final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<String> result, final long ttl,
        final TimeUnit timeUnit) {
    if (result.isDone()) {
        unsubscribe(subscribeFuture);//from   w ww.ja v  a 2  s  .  co  m
        return;
    }

    if (time.get() <= 0) {
        unsubscribe(subscribeFuture);
        result.trySuccess(null);
        return;
    }

    long timeoutDate = calcTimeout(ttl, timeUnit);
    final long current = System.currentTimeMillis();
    RFuture<String> tryAcquireFuture = tryAcquireAsync(permits, timeoutDate);
    tryAcquireFuture.addListener(new FutureListener<String>() {
        @Override
        public void operationComplete(Future<String> future) throws Exception {
            if (!future.isSuccess()) {
                unsubscribe(subscribeFuture);
                result.tryFailure(future.cause());
                return;
            }

            final Long nearestTimeout;
            String permitId = future.getNow();
            if (permitId != null) {
                if (!permitId.startsWith(":")) {
                    unsubscribe(subscribeFuture);
                    if (!result.trySuccess(permitId)) {
                        releaseAsync(permitId);
                    }
                    return;
                } else {
                    nearestTimeout = Long.valueOf(permitId.substring(1)) - System.currentTimeMillis();
                }
            } else {
                nearestTimeout = null;
            }

            long elapsed = System.currentTimeMillis() - current;
            time.addAndGet(-elapsed);

            if (time.get() <= 0) {
                unsubscribe(subscribeFuture);
                result.trySuccess(null);
                return;
            }

            // waiting for message
            final long current = System.currentTimeMillis();
            final RedissonLockEntry entry = getEntry();
            synchronized (entry) {
                if (entry.getLatch().tryAcquire()) {
                    tryAcquireAsync(time, permits, subscribeFuture, result, ttl, timeUnit);
                } else {
                    final AtomicReference<Timeout> waitTimeoutFutureRef = new AtomicReference<Timeout>();

                    final Timeout scheduledFuture;
                    if (nearestTimeout != null) {
                        scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
                            @Override
                            public void run(Timeout timeout) throws Exception {
                                if (waitTimeoutFutureRef.get() != null
                                        && !waitTimeoutFutureRef.get().cancel()) {
                                    return;
                                }

                                long elapsed = System.currentTimeMillis() - current;
                                time.addAndGet(-elapsed);

                                tryAcquireAsync(time, permits, subscribeFuture, result, ttl, timeUnit);
                            }
                        }, nearestTimeout, TimeUnit.MILLISECONDS);
                    } else {
                        scheduledFuture = null;
                    }

                    final Runnable listener = new Runnable() {
                        @Override
                        public void run() {
                            if (waitTimeoutFutureRef.get() != null && !waitTimeoutFutureRef.get().cancel()) {
                                entry.getLatch().release();
                                return;
                            }
                            if (scheduledFuture != null && !scheduledFuture.cancel()) {
                                entry.getLatch().release();
                                return;
                            }

                            long elapsed = System.currentTimeMillis() - current;
                            time.addAndGet(-elapsed);

                            tryAcquireAsync(time, permits, subscribeFuture, result, ttl, timeUnit);
                        }
                    };
                    entry.addListener(listener);

                    long t = time.get();
                    Timeout waitTimeoutFuture = commandExecutor.getConnectionManager()
                            .newTimeout(new TimerTask() {
                                @Override
                                public void run(Timeout timeout) throws Exception {
                                    if (scheduledFuture != null && !scheduledFuture.cancel()) {
                                        return;
                                    }

                                    synchronized (entry) {
                                        if (entry.removeListener(listener)) {
                                            long elapsed = System.currentTimeMillis() - current;
                                            time.addAndGet(-elapsed);

                                            tryAcquireAsync(time, permits, subscribeFuture, result, ttl,
                                                    timeUnit);
                                        }
                                    }
                                }
                            }, t, TimeUnit.MILLISECONDS);
                    waitTimeoutFutureRef.set(waitTimeoutFuture);
                }
            }
        }
    });

}

From source file:org.redisson.RedissonPermitExpirableSemaphore.java

License:Apache License

private void acquireAsync(final int permits, final RFuture<RedissonLockEntry> subscribeFuture,
        final RPromise<String> result, final long ttl, final TimeUnit timeUnit) {
    if (result.isDone()) {
        unsubscribe(subscribeFuture);//ww  w. j a v a2s .  c om
        return;
    }

    long timeoutDate = calcTimeout(ttl, timeUnit);
    RFuture<String> tryAcquireFuture = tryAcquireAsync(permits, timeoutDate);
    tryAcquireFuture.addListener(new FutureListener<String>() {
        @Override
        public void operationComplete(Future<String> future) throws Exception {
            if (!future.isSuccess()) {
                unsubscribe(subscribeFuture);
                result.tryFailure(future.cause());
                return;
            }

            final Long nearestTimeout;
            String permitId = future.getNow();
            if (permitId != null) {
                if (!permitId.startsWith(":")) {
                    unsubscribe(subscribeFuture);
                    if (!result.trySuccess(permitId)) {
                        releaseAsync(permitId);
                    }
                    return;
                } else {
                    nearestTimeout = Long.valueOf(permitId.substring(1)) - System.currentTimeMillis();
                }
            } else {
                nearestTimeout = null;
            }

            final RedissonLockEntry entry = getEntry();
            synchronized (entry) {
                if (entry.getLatch().tryAcquire(permits)) {
                    acquireAsync(permits, subscribeFuture, result, ttl, timeUnit);
                } else {
                    final Timeout scheduledFuture;
                    if (nearestTimeout != null) {
                        scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
                            @Override
                            public void run(Timeout timeout) throws Exception {
                                acquireAsync(permits, subscribeFuture, result, ttl, timeUnit);
                            }
                        }, nearestTimeout, TimeUnit.MILLISECONDS);
                    } else {
                        scheduledFuture = null;
                    }

                    Runnable listener = new Runnable() {
                        @Override
                        public void run() {
                            if (scheduledFuture != null && !scheduledFuture.cancel()) {
                                entry.getLatch().release();
                                return;
                            }
                            acquireAsync(permits, subscribeFuture, result, ttl, timeUnit);
                        }
                    };
                    entry.addListener(listener);
                }
            }
        }
    });
}

From source file:org.rzo.netty.ahessian.rpc.client.ReconnectHandler.java

License:Apache License

public void stop() {
    _stop = true;
    Timeout timeout = _timeout;
    _timeout = null;
    timeout.cancel();
}