Example usage for io.netty.util.concurrent Future getNow

List of usage examples for io.netty.util.concurrent Future getNow

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future getNow.

Prototype

V getNow();

Source Link

Document

Return the result without blocking.

Usage

From source file:org.redisson.RedissonBlockingFairQueue.java

License:Apache License

@Override
public RFuture<V> pollAsync(final long timeout, final TimeUnit unit) {
    final long startTime = System.currentTimeMillis();
    final RPromise<V> promise = newPromise();

    RFuture<Long> tryAcquireFuture = tryAcquireAsync();
    tryAcquireFuture.addListener(new FutureListener<Long>() {
        @Override/*from   w  w w . java2 s  .com*/
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                promise.tryFailure(future.cause());
                return;
            }

            Long currentTimeout = future.getNow();
            if (currentTimeout == null) {
                long spentTime = System.currentTimeMillis() - startTime;
                long remainTime = unit.toMillis(timeout) - spentTime;
                if (remainTime > 0) {
                    final RFuture<V> pollFuture = RedissonBlockingFairQueue.super.pollAsync(remainTime,
                            TimeUnit.MILLISECONDS);
                    pollFuture.addListener(new FutureListener<V>() {
                        @Override
                        public void operationComplete(Future<V> future) throws Exception {
                            if (!future.isSuccess()) {
                                promise.tryFailure(future.cause());
                                return;
                            }

                            promise.trySuccess(future.getNow());
                        }
                    });
                } else {
                    promise.trySuccess(null);
                }
            } else {
                long spentTime = System.currentTimeMillis() - startTime;
                long remainTime = unit.toMillis(timeout) - spentTime;
                remainTime = Math.min(remainTime, currentTimeout);
                if (remainTime <= 0) {
                    promise.trySuccess(null);
                    return;
                }

                final RFuture<RedissonLockEntry> subscribeFuture = subscribe();
                final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
                subscribeFuture.addListener(new FutureListener<RedissonLockEntry>() {
                    @Override
                    public void operationComplete(Future<RedissonLockEntry> future) throws Exception {
                        if (!future.isSuccess()) {
                            promise.tryFailure(future.cause());
                            return;
                        }

                        if (futureRef.get() != null) {
                            futureRef.get().cancel();
                        }

                        tryPollAsync(startTime, timeout, unit, subscribeFuture, promise);
                    }
                });
                if (!subscribeFuture.isDone()) {
                    Timeout scheduledFuture = commandExecutor.getConnectionManager()
                            .newTimeout(new TimerTask() {
                                @Override
                                public void run(Timeout timeout) throws Exception {
                                    if (!subscribeFuture.isDone()) {
                                        subscribeFuture.cancel(false);
                                        promise.trySuccess(null);
                                    }
                                }
                            }, remainTime, TimeUnit.MILLISECONDS);
                    futureRef.set(scheduledFuture);
                }
            }
        }
    });

    return promise;
}

From source file:org.redisson.RedissonBlockingFairQueue.java

License:Apache License

private void tryTakeAsync(final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<V> promise) {
    if (promise.isDone()) {
        unsubscribe(subscribeFuture);//from w  w  w .j a  v  a  2  s . c  o m
        return;
    }

    RFuture<Long> tryAcquireFuture = tryAcquireAsync();
    tryAcquireFuture.addListener(new FutureListener<Long>() {
        @Override
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                unsubscribe(subscribeFuture);
                promise.tryFailure(future.cause());
                return;
            }

            Long currentTimeout = future.getNow();
            if (currentTimeout == null) {
                final RFuture<V> pollFuture = RedissonBlockingFairQueue.super.takeAsync();
                pollFuture.addListener(new FutureListener<V>() {
                    @Override
                    public void operationComplete(Future<V> future) throws Exception {
                        unsubscribe(subscribeFuture);
                        if (!future.isSuccess()) {
                            promise.tryFailure(future.cause());
                            return;
                        }

                        promise.trySuccess(future.getNow());
                    }
                });
            } else {
                final RedissonLockEntry entry = getEntry();
                synchronized (entry) {
                    if (entry.getLatch().tryAcquire()) {
                        tryTakeAsync(subscribeFuture, promise);
                    } else {
                        final AtomicBoolean executed = new AtomicBoolean();
                        final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
                        final Runnable listener = new Runnable() {
                            @Override
                            public void run() {
                                executed.set(true);
                                if (futureRef.get() != null) {
                                    futureRef.get().cancel();
                                }

                                tryTakeAsync(subscribeFuture, promise);
                            }
                        };
                        entry.addListener(listener);

                        if (!executed.get()) {
                            Timeout scheduledFuture = commandExecutor.getConnectionManager()
                                    .newTimeout(new TimerTask() {
                                        @Override
                                        public void run(Timeout t) throws Exception {
                                            synchronized (entry) {
                                                if (entry.removeListener(listener)) {
                                                    tryTakeAsync(subscribeFuture, promise);
                                                }
                                            }
                                        }
                                    }, currentTimeout, TimeUnit.MILLISECONDS);
                            futureRef.set(scheduledFuture);
                        }
                    }
                }
            }
        };
    });
}

From source file:org.redisson.RedissonBlockingFairQueue.java

License:Apache License

private void tryPollAsync(final long startTime, final long timeout, final TimeUnit unit,
        final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<V> promise) {
    if (promise.isDone()) {
        unsubscribe(subscribeFuture);/*from  w w  w  .java2 s . c o  m*/
        return;
    }

    long spentTime = System.currentTimeMillis() - startTime;
    long remainTime = unit.toMillis(timeout) - spentTime;
    if (remainTime <= 0) {
        unsubscribe(subscribeFuture);
        promise.trySuccess(null);
        return;
    }

    RFuture<Long> tryAcquireFuture = tryAcquireAsync();
    tryAcquireFuture.addListener(new FutureListener<Long>() {
        @Override
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                unsubscribe(subscribeFuture);
                promise.tryFailure(future.cause());
                return;
            }

            Long currentTimeout = future.getNow();
            if (currentTimeout == null) {
                long spentTime = System.currentTimeMillis() - startTime;
                long remainTime = unit.toMillis(timeout) - spentTime;
                if (remainTime > 0) {
                    final RFuture<V> pollFuture = RedissonBlockingFairQueue.super.pollAsync(remainTime,
                            TimeUnit.MILLISECONDS);
                    pollFuture.addListener(new FutureListener<V>() {
                        @Override
                        public void operationComplete(Future<V> future) throws Exception {
                            unsubscribe(subscribeFuture);
                            if (!future.isSuccess()) {
                                promise.tryFailure(future.cause());
                                return;
                            }

                            promise.trySuccess(future.getNow());
                        }
                    });
                } else {
                    unsubscribe(subscribeFuture);
                    promise.trySuccess(null);
                }
            } else {
                final RedissonLockEntry entry = getEntry();
                synchronized (entry) {
                    if (entry.getLatch().tryAcquire()) {
                        tryPollAsync(startTime, timeout, unit, subscribeFuture, promise);
                    } else {
                        final AtomicBoolean executed = new AtomicBoolean();
                        final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
                        final Runnable listener = new Runnable() {
                            @Override
                            public void run() {
                                executed.set(true);
                                if (futureRef.get() != null) {
                                    futureRef.get().cancel();
                                }

                                tryPollAsync(startTime, timeout, unit, subscribeFuture, promise);
                            }
                        };
                        entry.addListener(listener);

                        if (!executed.get()) {
                            long spentTime = System.currentTimeMillis() - startTime;
                            long remainTime = unit.toMillis(timeout) - spentTime;
                            Timeout scheduledFuture = commandExecutor.getConnectionManager()
                                    .newTimeout(new TimerTask() {
                                        @Override
                                        public void run(Timeout t) throws Exception {
                                            synchronized (entry) {
                                                if (entry.removeListener(listener)) {
                                                    tryPollAsync(startTime, timeout, unit, subscribeFuture,
                                                            promise);
                                                }
                                            }
                                        }
                                    }, remainTime, TimeUnit.MILLISECONDS);
                            futureRef.set(scheduledFuture);
                        }
                    }
                }
            }
        };
    });
}

From source file:org.redisson.RedissonBlockingFairQueue.java

License:Apache License

@Override
public RFuture<V> pollLastAndOfferFirstToAsync(final String queueName, final long timeout,
        final TimeUnit unit) {
    final long startTime = System.currentTimeMillis();
    final RPromise<V> promise = newPromise();

    RFuture<Long> tryAcquireFuture = tryAcquireAsync();
    tryAcquireFuture.addListener(new FutureListener<Long>() {
        @Override/*from w ww  .  ja  v  a  2  s. c o m*/
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                promise.tryFailure(future.cause());
                return;
            }

            Long currentTimeout = future.getNow();
            if (currentTimeout == null) {
                long spentTime = System.currentTimeMillis() - startTime;
                long remainTime = unit.toMillis(timeout) - spentTime;
                if (remainTime > 0) {
                    final RFuture<V> pollFuture = RedissonBlockingFairQueue.super.pollLastAndOfferFirstToAsync(
                            queueName, remainTime, TimeUnit.MILLISECONDS);
                    pollFuture.addListener(new FutureListener<V>() {
                        @Override
                        public void operationComplete(Future<V> future) throws Exception {
                            if (!future.isSuccess()) {
                                promise.tryFailure(future.cause());
                                return;
                            }

                            promise.trySuccess(future.getNow());
                        }
                    });
                } else {
                    promise.trySuccess(null);
                }
            } else {
                long spentTime = System.currentTimeMillis() - startTime;
                long remainTime = unit.toMillis(timeout) - spentTime;
                remainTime = Math.min(remainTime, currentTimeout);
                if (remainTime <= 0) {
                    promise.trySuccess(null);
                    return;
                }

                final RFuture<RedissonLockEntry> subscribeFuture = subscribe();
                final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
                subscribeFuture.addListener(new FutureListener<RedissonLockEntry>() {
                    @Override
                    public void operationComplete(Future<RedissonLockEntry> future) throws Exception {
                        if (!future.isSuccess()) {
                            promise.tryFailure(future.cause());
                            return;
                        }

                        if (futureRef.get() != null) {
                            futureRef.get().cancel();
                        }

                        tryPollLastAndOfferFirstToAsync(startTime, timeout, unit, subscribeFuture, promise,
                                queueName);
                    }
                });
                if (!subscribeFuture.isDone()) {
                    Timeout scheduledFuture = commandExecutor.getConnectionManager()
                            .newTimeout(new TimerTask() {
                                @Override
                                public void run(Timeout timeout) throws Exception {
                                    if (!subscribeFuture.isDone()) {
                                        subscribeFuture.cancel(false);
                                        promise.trySuccess(null);
                                    }
                                }
                            }, remainTime, TimeUnit.MILLISECONDS);
                    futureRef.set(scheduledFuture);
                }
            }
        }
    });

    return promise;
}

From source file:org.redisson.RedissonBlockingFairQueue.java

License:Apache License

private void tryPollLastAndOfferFirstToAsync(final long startTime, final long timeout, final TimeUnit unit,
        final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<V> promise, final String queueName) {
    if (promise.isDone()) {
        unsubscribe(subscribeFuture);/*w ww . j  a va 2 s.c om*/
        return;
    }

    long spentTime = System.currentTimeMillis() - startTime;
    long remainTime = unit.toMillis(timeout) - spentTime;
    if (remainTime <= 0) {
        unsubscribe(subscribeFuture);
        promise.trySuccess(null);
        return;
    }

    RFuture<Long> tryAcquireFuture = tryAcquireAsync();
    tryAcquireFuture.addListener(new FutureListener<Long>() {
        @Override
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                unsubscribe(subscribeFuture);
                promise.tryFailure(future.cause());
                return;
            }

            Long currentTimeout = future.getNow();
            if (currentTimeout == null) {
                long spentTime = System.currentTimeMillis() - startTime;
                long remainTime = unit.toMillis(timeout) - spentTime;
                if (remainTime > 0) {
                    final RFuture<V> pollFuture = RedissonBlockingFairQueue.super.pollLastAndOfferFirstToAsync(
                            queueName, remainTime, TimeUnit.MILLISECONDS);
                    pollFuture.addListener(new FutureListener<V>() {
                        @Override
                        public void operationComplete(Future<V> future) throws Exception {
                            unsubscribe(subscribeFuture);
                            if (!future.isSuccess()) {
                                promise.tryFailure(future.cause());
                                return;
                            }

                            promise.trySuccess(future.getNow());
                        }
                    });
                } else {
                    unsubscribe(subscribeFuture);
                    promise.trySuccess(null);
                }
            } else {
                final RedissonLockEntry entry = getEntry();
                synchronized (entry) {
                    if (entry.getLatch().tryAcquire()) {
                        tryPollAsync(startTime, timeout, unit, subscribeFuture, promise);
                    } else {
                        final AtomicBoolean executed = new AtomicBoolean();
                        final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
                        final Runnable listener = new Runnable() {
                            @Override
                            public void run() {
                                executed.set(true);
                                if (futureRef.get() != null) {
                                    futureRef.get().cancel();
                                }

                                tryPollLastAndOfferFirstToAsync(startTime, timeout, unit, subscribeFuture,
                                        promise, queueName);
                            }
                        };
                        entry.addListener(listener);

                        if (!executed.get()) {
                            long spentTime = System.currentTimeMillis() - startTime;
                            long remainTime = unit.toMillis(timeout) - spentTime;
                            Timeout scheduledFuture = commandExecutor.getConnectionManager()
                                    .newTimeout(new TimerTask() {
                                        @Override
                                        public void run(Timeout t) throws Exception {
                                            synchronized (entry) {
                                                if (entry.removeListener(listener)) {
                                                    tryPollLastAndOfferFirstToAsync(startTime, timeout, unit,
                                                            subscribeFuture, promise, queueName);
                                                }
                                            }
                                        }
                                    }, remainTime, TimeUnit.MILLISECONDS);
                            futureRef.set(scheduledFuture);
                        }
                    }
                }
            }
        };
    });
}

From source file:org.redisson.RedissonFairLock.java

License:Apache License

@Override
protected void unsubscribe(Future<RedissonLockEntry> future, long threadId) {
    PUBSUB.unsubscribe(future.getNow(), getEntryName() + ":" + threadId,
            getChannelName() + ":" + getLockName(threadId), commandExecutor.getConnectionManager());
}

From source file:org.redisson.RedissonKeys.java

License:Apache License

@Override
public RFuture<Long> deleteByPatternAsync(String pattern) {
    if (!commandExecutor.getConnectionManager().isClusterMode()) {
        return commandExecutor.evalWriteAsync((String) null, null, RedisCommands.EVAL_LONG,
                "local keys = redis.call('keys', ARGV[1]) " + "local n = 0 " + "for i=1, #keys,5000 do "
                        + "n = n + redis.call('del', unpack(keys, i, math.min(i+4999, table.getn(keys)))) "
                        + "end " + "return n;",
                Collections.emptyList(), pattern);
    }//from   w w  w .  j av  a2s  .  c  o  m

    final RPromise<Long> result = commandExecutor.getConnectionManager().newPromise();
    final AtomicReference<Throwable> failed = new AtomicReference<Throwable>();
    final AtomicLong count = new AtomicLong();
    Set<MasterSlaveEntry> entries = commandExecutor.getConnectionManager().getEntrySet();
    final AtomicLong executed = new AtomicLong(entries.size());
    final FutureListener<Long> listener = new FutureListener<Long>() {
        @Override
        public void operationComplete(Future<Long> future) throws Exception {
            if (future.isSuccess()) {
                count.addAndGet(future.getNow());
            } else {
                failed.set(future.cause());
            }

            checkExecution(result, failed, count, executed);
        }
    };

    for (MasterSlaveEntry entry : entries) {
        RFuture<Collection<String>> findFuture = commandExecutor.readAsync(entry, null, RedisCommands.KEYS,
                pattern);
        findFuture.addListener(new FutureListener<Collection<String>>() {
            @Override
            public void operationComplete(Future<Collection<String>> future) throws Exception {
                if (!future.isSuccess()) {
                    failed.set(future.cause());
                    checkExecution(result, failed, count, executed);
                    return;
                }

                Collection<String> keys = future.getNow();
                if (keys.isEmpty()) {
                    checkExecution(result, failed, count, executed);
                    return;
                }

                RFuture<Long> deleteFuture = deleteAsync(keys.toArray(new String[keys.size()]));
                deleteFuture.addListener(listener);
            }
        });
    }

    return result;
}

From source file:org.redisson.RedissonMapCache.java

License:Apache License

public RFuture<MapScanResult<ScanObjectEntry, ScanObjectEntry>> scanIteratorAsync(final String name,
        InetSocketAddress client, long startPos) {
    RedisCommand<MapCacheScanResult<Object, Object>> EVAL_HSCAN = new RedisCommand<MapCacheScanResult<Object, Object>>(
            "EVAL", new ListMultiDecoder(new LongMultiDecoder(), new ObjectMapDecoder(new MapScanCodec(codec)),
                    new ObjectListDecoder(codec), new MapCacheScanResultReplayDecoder()),
            ValueType.MAP);//from ww  w .j  ava2  s .c o  m
    RFuture<MapCacheScanResult<ScanObjectEntry, ScanObjectEntry>> f = commandExecutor.evalReadAsync(client,
            name, codec, EVAL_HSCAN,
            "local result = {}; " + "local idleKeys = {}; "
                    + "local res = redis.call('hscan', KEYS[1], ARGV[2]); "
                    + "local currentTime = tonumber(ARGV[1]); " + "for i, value in ipairs(res[2]) do "
                    + "if i % 2 == 0 then " + "local key = res[2][i-1]; "
                    + "local expireDate = 92233720368547758; "
                    + "local expireDateScore = redis.call('zscore', KEYS[2], key); "
                    + "if expireDateScore ~= false then " + "expireDate = tonumber(expireDateScore) " + "end; "

                    + "local t, val = struct.unpack('dLc0', value); " + "if t ~= 0 then "
                    + "local expireIdle = redis.call('zscore', KEYS[3], key); " + "if expireIdle ~= false then "
                    + "if tonumber(expireIdle) > currentTime and expireDate > currentTime then "
                    + "table.insert(idleKeys, key); " + "end; "
                    + "expireDate = math.min(expireDate, tonumber(expireIdle)) " + "end; " + "end; "

                    + "if expireDate > currentTime then " + "table.insert(result, key); "
                    + "table.insert(result, val); " + "end; " + "end; " + "end;"
                    + "return {res[1], result, idleKeys};",
            Arrays.<Object>asList(name, getTimeoutSetName(name), getIdleSetName(name)),
            System.currentTimeMillis(), startPos);

    f.addListener(new FutureListener<MapCacheScanResult<ScanObjectEntry, ScanObjectEntry>>() {
        @Override
        public void operationComplete(Future<MapCacheScanResult<ScanObjectEntry, ScanObjectEntry>> future)
                throws Exception {
            if (future.isSuccess()) {
                MapCacheScanResult<ScanObjectEntry, ScanObjectEntry> res = future.getNow();
                if (res.getIdleKeys().isEmpty()) {
                    return;
                }

                List<Object> args = new ArrayList<Object>(res.getIdleKeys().size() + 1);
                args.add(System.currentTimeMillis());
                args.addAll(res.getIdleKeys());

                commandExecutor.evalWriteAsync(name, codec,
                        new RedisCommand<Map<Object, Object>>("EVAL", new MapGetAllDecoder(args, 1), 7,
                                ValueType.MAP_KEY, ValueType.MAP_VALUE),
                        "local currentTime = tonumber(table.remove(ARGV, 1)); " // index is the first parameter
                                + "local map = redis.call('hmget', KEYS[1], unpack(ARGV)); "
                                + "for i = #map, 1, -1 do " + "local value = map[i]; "
                                + "if value ~= false then " + "local key = ARGV[i]; "
                                + "local t, val = struct.unpack('dLc0', value); "

                                + "if t ~= 0 then " + "local expireIdle = redis.call('zscore', KEYS[2], key); "
                                + "if expireIdle ~= false then " + "if tonumber(expireIdle) > currentTime then "
                                + "local value = struct.pack('dLc0', t, string.len(val), val); "
                                + "redis.call('hset', KEYS[1], key, value); "
                                + "redis.call('zadd', KEYS[2], t + currentTime, key); " + "end; " + "end; "
                                + "end; " + "end; " + "end; ",
                        Arrays.<Object>asList(name, getIdleSetName(name)), args.toArray());

            }
        }
    });

    return (RFuture<MapScanResult<ScanObjectEntry, ScanObjectEntry>>) (Object) f;
}

From source file:org.redisson.RedissonPatternTopic.java

License:Apache License

private int addListener(RedisPubSubListener<M> pubSubListener) {
    Future<PubSubConnectionEntry> future = commandExecutor.getConnectionManager().psubscribe(name, codec);
    future.syncUninterruptibly();//from ww w.ja  v a  2  s  . c  o  m
    PubSubConnectionEntry entry = future.getNow();
    synchronized (entry) {
        if (entry.isActive()) {
            entry.addListener(name, pubSubListener);
            return System.identityHashCode(pubSubListener);
        }
    }
    // entry is inactive trying add again
    return addListener(pubSubListener);
}

From source file:org.redisson.RedissonPermitExpirableSemaphore.java

License:Apache License

private RFuture<String> acquireAsync(final int permits, final long ttl, final TimeUnit timeUnit) {
    final RPromise<String> result = newPromise();
    long timeoutDate = calcTimeout(ttl, timeUnit);
    RFuture<String> tryAcquireFuture = tryAcquireAsync(permits, timeoutDate);
    tryAcquireFuture.addListener(new FutureListener<String>() {
        @Override/*from w  ww .  j  a v  a  2 s  . co  m*/
        public void operationComplete(Future<String> future) throws Exception {
            if (!future.isSuccess()) {
                result.tryFailure(future.cause());
                return;
            }

            String permitId = future.getNow();
            if (permitId != null && !permitId.startsWith(":")) {
                if (!result.trySuccess(permitId)) {
                    releaseAsync(permitId);
                }
                return;
            }

            final RFuture<RedissonLockEntry> subscribeFuture = subscribe();
            subscribeFuture.addListener(new FutureListener<RedissonLockEntry>() {
                @Override
                public void operationComplete(Future<RedissonLockEntry> future) throws Exception {
                    if (!future.isSuccess()) {
                        result.tryFailure(future.cause());
                        return;
                    }

                    acquireAsync(permits, subscribeFuture, result, ttl, timeUnit);
                }

            });
        }
    });
    return result;
}