Search in sources :

Example 31 with RFuture

use of org.redisson.api.RFuture in project redisson by redisson.

the class RedissonBatchTest method testOrdering.

@Test
public void testOrdering() throws InterruptedException {
    ExecutorService e = Executors.newFixedThreadPool(16);
    final RBatch batch = redisson.createBatch();
    final AtomicLong index = new AtomicLong(-1);
    final List<RFuture<Long>> futures = new CopyOnWriteArrayList<>();
    for (int i = 0; i < 500; i++) {
        futures.add(null);
    }
    for (int i = 0; i < 500; i++) {
        final int j = i;
        e.execute(new Runnable() {

            @Override
            public void run() {
                synchronized (RedissonBatchTest.this) {
                    int i = (int) index.incrementAndGet();
                    int ind = j % 3;
                    RFuture<Long> f1 = batch.getAtomicLong("test" + ind).addAndGetAsync(j);
                    futures.set(i, f1);
                }
            }
        });
    }
    e.shutdown();
    Assert.assertTrue(e.awaitTermination(30, TimeUnit.SECONDS));
    List<?> s = batch.execute();
    int i = 0;
    for (Object element : s) {
        RFuture<Long> a = futures.get(i);
        Assert.assertEquals(a.getNow(), element);
        i++;
    }
}
Also used : RFuture(org.redisson.api.RFuture) AtomicLong(java.util.concurrent.atomic.AtomicLong) RBatch(org.redisson.api.RBatch) ExecutorService(java.util.concurrent.ExecutorService) AtomicLong(java.util.concurrent.atomic.AtomicLong) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.Test)

Example 32 with RFuture

use of org.redisson.api.RFuture in project redisson by redisson.

the class RedissonExecutorService method poll.

private <T> Future<T> poll(List<Future<T>> futures, long timeout, TimeUnit timeUnit) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Future<T>> result = new AtomicReference<Future<T>>();
    FutureListener<T> listener = new FutureListener<T>() {

        @Override
        public void operationComplete(io.netty.util.concurrent.Future<T> future) throws Exception {
            latch.countDown();
            result.compareAndSet(null, future);
        }
    };
    for (Future<T> future : futures) {
        RFuture<T> f = (RFuture<T>) future;
        f.addListener(listener);
    }
    if (timeout == -1) {
        latch.await();
    } else {
        latch.await(timeout, timeUnit);
    }
    for (Future<T> future : futures) {
        RFuture<T> f = (RFuture<T>) future;
        f.removeListener(listener);
    }
    return result.get();
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) ScheduledFuture(java.util.concurrent.ScheduledFuture) RScheduledFuture(org.redisson.api.RScheduledFuture) Future(java.util.concurrent.Future) RedissonScheduledFuture(org.redisson.executor.RedissonScheduledFuture) RFuture(org.redisson.api.RFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) RFuture(org.redisson.api.RFuture)

Example 33 with RFuture

use of org.redisson.api.RFuture in project redisson by redisson.

the class RedissonKeys method deleteAsync.

@Override
public RFuture<Long> deleteAsync(String... keys) {
    if (!commandExecutor.getConnectionManager().isClusterMode()) {
        return commandExecutor.writeAsync(null, RedisCommands.DEL, keys);
    }
    Map<MasterSlaveEntry, List<String>> range2key = new HashMap<MasterSlaveEntry, List<String>>();
    for (String key : keys) {
        int slot = commandExecutor.getConnectionManager().calcSlot(key);
        for (MasterSlaveEntry entry : commandExecutor.getConnectionManager().getEntrySet()) {
            List<String> list = range2key.get(entry);
            if (list == null) {
                list = new ArrayList<String>();
                range2key.put(entry, list);
            }
            list.add(key);
        }
    }
    final RPromise<Long> result = commandExecutor.getConnectionManager().newPromise();
    final AtomicReference<Throwable> failed = new AtomicReference<Throwable>();
    final AtomicLong count = new AtomicLong();
    final AtomicLong executed = new AtomicLong(range2key.size());
    FutureListener<List<?>> listener = new FutureListener<List<?>>() {

        @Override
        public void operationComplete(Future<List<?>> future) throws Exception {
            if (future.isSuccess()) {
                List<Long> result = (List<Long>) future.get();
                for (Long res : result) {
                    count.addAndGet(res);
                }
            } else {
                failed.set(future.cause());
            }
            checkExecution(result, failed, count, executed);
        }
    };
    for (Entry<MasterSlaveEntry, List<String>> entry : range2key.entrySet()) {
        // executes in batch due to CROSSLOT error
        CommandBatchService executorService = new CommandBatchService(commandExecutor.getConnectionManager());
        for (String key : entry.getValue()) {
            executorService.writeAsync(entry.getKey(), null, RedisCommands.DEL, key);
        }
        RFuture<List<?>> future = executorService.executeAsync();
        future.addListener(listener);
    }
    return result;
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) HashMap(java.util.HashMap) CommandBatchService(org.redisson.command.CommandBatchService) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicLong(java.util.concurrent.atomic.AtomicLong) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) AtomicLong(java.util.concurrent.atomic.AtomicLong) RFuture(org.redisson.api.RFuture) Future(io.netty.util.concurrent.Future) ArrayList(java.util.ArrayList) List(java.util.List)

Example 34 with RFuture

use of org.redisson.api.RFuture in project redisson by redisson.

the class RedissonBlockingFairQueue method tryPollAsync.

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);
        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);
                        }
                    }
                }
            }
        }

        ;
    });
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) Timeout(io.netty.util.Timeout) AtomicReference(java.util.concurrent.atomic.AtomicReference) RFuture(org.redisson.api.RFuture) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TimerTask(io.netty.util.TimerTask) RFuture(org.redisson.api.RFuture) Future(io.netty.util.concurrent.Future)

Example 35 with RFuture

use of org.redisson.api.RFuture in project redisson by redisson.

the class RedissonBaseAdder method resetAsync.

public RFuture<Void> resetAsync() {
    String id = generateId();
    RFuture<Long> future = topic.publishAsync(CLEAR_MSG + ":" + id);
    RSemaphore semaphore = getSemaphore(id);
    CompletionStage<Void> f = future.thenCompose(r -> semaphore.acquireAsync(r.intValue())).thenCompose(r -> semaphore.deleteAsync().thenApply(res -> null));
    return new CompletableFutureWrapper<>(f);
}
Also used : RFuture(org.redisson.api.RFuture) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) ByteBufUtil(io.netty.buffer.ByteBufUtil) CommandAsyncExecutor(org.redisson.command.CommandAsyncExecutor) Logger(org.slf4j.Logger) StringCodec(org.redisson.client.codec.StringCodec) java.util.concurrent(java.util.concurrent) RTopic(org.redisson.api.RTopic) LoggerFactory(org.slf4j.LoggerFactory) RSemaphore(org.redisson.api.RSemaphore) RedissonClient(org.redisson.api.RedissonClient) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) RSemaphore(org.redisson.api.RSemaphore)

Aggregations

RFuture (org.redisson.api.RFuture)44 FutureListener (io.netty.util.concurrent.FutureListener)19 Future (io.netty.util.concurrent.Future)17 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)12 CompletableFutureWrapper (org.redisson.misc.CompletableFutureWrapper)12 Logger (org.slf4j.Logger)12 LoggerFactory (org.slf4j.LoggerFactory)12 StringCodec (org.redisson.client.codec.StringCodec)11 MasterSlaveEntry (org.redisson.connection.MasterSlaveEntry)11 RPromise (org.redisson.misc.RPromise)11 RedissonPromise (org.redisson.misc.RedissonPromise)11 ArrayList (java.util.ArrayList)10 AtomicLong (java.util.concurrent.atomic.AtomicLong)10 RedisClient (org.redisson.client.RedisClient)10 RedisCommands (org.redisson.client.protocol.RedisCommands)10 java.util.concurrent (java.util.concurrent)9 CommandAsyncExecutor (org.redisson.command.CommandAsyncExecutor)9 Timeout (io.netty.util.Timeout)8 java.util (java.util)8