Search in sources :

Example 21 with Timeout

use of io.netty.util.Timeout in project redisson by redisson.

the class RedissonLock method tryLockAsync.

public RFuture<Boolean> tryLockAsync(final long waitTime, final long leaseTime, final TimeUnit unit, final long currentThreadId) {
    final RPromise<Boolean> result = newPromise();
    final AtomicLong time = new AtomicLong(unit.toMillis(waitTime));
    final long currentTime = System.currentTimeMillis();
    RFuture<Long> ttlFuture = tryAcquireAsync(leaseTime, unit, currentThreadId);
    ttlFuture.addListener(new FutureListener<Long>() {

        @Override
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                result.tryFailure(future.cause());
                return;
            }
            Long ttl = future.getNow();
            // lock acquired
            if (ttl == null) {
                if (!result.trySuccess(true)) {
                    unlockAsync(currentThreadId);
                }
                return;
            }
            long elapsed = System.currentTimeMillis() - currentTime;
            time.addAndGet(-elapsed);
            if (time.get() <= 0) {
                trySuccessFalse(currentThreadId, result);
                return;
            }
            final long current = System.currentTimeMillis();
            final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
            final RFuture<RedissonLockEntry> subscribeFuture = subscribe(currentThreadId);
            subscribeFuture.addListener(new FutureListener<RedissonLockEntry>() {

                @Override
                public void operationComplete(Future<RedissonLockEntry> future) throws Exception {
                    if (!future.isSuccess()) {
                        result.tryFailure(future.cause());
                        return;
                    }
                    if (futureRef.get() != null) {
                        futureRef.get().cancel();
                    }
                    long elapsed = System.currentTimeMillis() - current;
                    time.addAndGet(-elapsed);
                    tryLockAsync(time, leaseTime, unit, subscribeFuture, result, currentThreadId);
                }
            });
            if (!subscribeFuture.isDone()) {
                Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        if (!subscribeFuture.isDone()) {
                            subscribeFuture.cancel(false);
                            trySuccessFalse(currentThreadId, result);
                        }
                    }
                }, time.get(), TimeUnit.MILLISECONDS);
                futureRef.set(scheduledFuture);
            }
        }
    });
    return result;
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) Timeout(io.netty.util.Timeout) AtomicReference(java.util.concurrent.atomic.AtomicReference) RFuture(org.redisson.api.RFuture) AtomicLong(java.util.concurrent.atomic.AtomicLong) TimerTask(io.netty.util.TimerTask) AtomicLong(java.util.concurrent.atomic.AtomicLong) RFuture(org.redisson.api.RFuture) Future(io.netty.util.concurrent.Future) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 22 with Timeout

use of io.netty.util.Timeout in project redisson by redisson.

the class RedissonLock method tryLockAsync.

private void tryLockAsync(final AtomicLong time, final long leaseTime, final TimeUnit unit, final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<Boolean> result, final long currentThreadId) {
    if (result.isDone()) {
        unsubscribe(subscribeFuture, currentThreadId);
        return;
    }
    if (time.get() <= 0) {
        unsubscribe(subscribeFuture, currentThreadId);
        trySuccessFalse(currentThreadId, result);
        return;
    }
    final long current = System.currentTimeMillis();
    RFuture<Long> ttlFuture = tryAcquireAsync(leaseTime, unit, currentThreadId);
    ttlFuture.addListener(new FutureListener<Long>() {

        @Override
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                unsubscribe(subscribeFuture, currentThreadId);
                result.tryFailure(future.cause());
                return;
            }
            Long ttl = future.getNow();
            // lock acquired
            if (ttl == null) {
                unsubscribe(subscribeFuture, currentThreadId);
                if (!result.trySuccess(true)) {
                    unlockAsync(currentThreadId);
                }
                return;
            }
            long elapsed = System.currentTimeMillis() - current;
            time.addAndGet(-elapsed);
            if (time.get() <= 0) {
                unsubscribe(subscribeFuture, currentThreadId);
                trySuccessFalse(currentThreadId, result);
                return;
            }
            // waiting for message
            final long current = System.currentTimeMillis();
            final RedissonLockEntry entry = getEntry(currentThreadId);
            synchronized (entry) {
                if (entry.getLatch().tryAcquire()) {
                    tryLockAsync(time, leaseTime, unit, subscribeFuture, result, currentThreadId);
                } 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();
                            }
                            long elapsed = System.currentTimeMillis() - current;
                            time.addAndGet(-elapsed);
                            tryLockAsync(time, leaseTime, unit, subscribeFuture, result, currentThreadId);
                        }
                    };
                    entry.addListener(listener);
                    long t = time.get();
                    if (ttl >= 0 && ttl < time.get()) {
                        t = ttl;
                    }
                    if (!executed.get()) {
                        Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {

                            @Override
                            public void run(Timeout timeout) throws Exception {
                                synchronized (entry) {
                                    if (entry.removeListener(listener)) {
                                        long elapsed = System.currentTimeMillis() - current;
                                        time.addAndGet(-elapsed);
                                        tryLockAsync(time, leaseTime, unit, subscribeFuture, result, currentThreadId);
                                    }
                                }
                            }
                        }, t, TimeUnit.MILLISECONDS);
                        futureRef.set(scheduledFuture);
                    }
                }
            }
        }
    });
}
Also used : Timeout(io.netty.util.Timeout) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TimerTask(io.netty.util.TimerTask) AtomicLong(java.util.concurrent.atomic.AtomicLong)

Example 23 with Timeout

use of io.netty.util.Timeout in project redisson by redisson.

the class RedissonPermitExpirableSemaphore method tryAcquireAsync.

private RFuture<String> tryAcquireAsync(final int permits, long waitTime, final long ttl, final TimeUnit timeUnit) {
    final RPromise<String> result = newPromise();
    final AtomicLong time = new AtomicLong(timeUnit.toMillis(waitTime));
    final long current = System.currentTimeMillis();
    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()) {
                result.tryFailure(future.cause());
                return;
            }
            String permitId = future.getNow();
            if (permitId != null && !permitId.startsWith(":")) {
                if (!result.trySuccess(permitId)) {
                    releaseAsync(permitId);
                }
                return;
            }
            long elapsed = System.currentTimeMillis() - current;
            time.addAndGet(-elapsed);
            if (time.get() <= 0) {
                result.trySuccess(null);
                return;
            }
            final long current = System.currentTimeMillis();
            final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
            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;
                    }
                    if (futureRef.get() != null) {
                        futureRef.get().cancel();
                    }
                    long elapsed = System.currentTimeMillis() - current;
                    time.addAndGet(-elapsed);
                    tryAcquireAsync(time, permits, subscribeFuture, result, ttl, timeUnit);
                }
            });
            if (!subscribeFuture.isDone()) {
                Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        if (!subscribeFuture.isDone()) {
                            result.trySuccess(null);
                        }
                    }
                }, time.get(), TimeUnit.MILLISECONDS);
                futureRef.set(scheduledFuture);
            }
        }
    });
    return result;
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) Timeout(io.netty.util.Timeout) AtomicReference(java.util.concurrent.atomic.AtomicReference) RFuture(org.redisson.api.RFuture) AtomicLong(java.util.concurrent.atomic.AtomicLong) TimerTask(io.netty.util.TimerTask) RFuture(org.redisson.api.RFuture) Future(io.netty.util.concurrent.Future)

Example 24 with Timeout

use of io.netty.util.Timeout in project netty-socketio by mrniko.

the class HashedWheelTimeoutScheduler method scheduleCallback.

@Override
public void scheduleCallback(final SchedulerKey key, final Runnable runnable, long delay, TimeUnit unit) {
    Timeout timeout = executorService.newTimeout(new TimerTask() {

        @Override
        public void run(Timeout timeout) throws Exception {
            ctx.executor().execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        runnable.run();
                    } finally {
                        scheduledFutures.remove(key);
                    }
                }
            });
        }
    }, delay, unit);
    replaceScheduledFuture(key, timeout);
}
Also used : TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout)

Example 25 with Timeout

use of io.netty.util.Timeout in project pulsar by yahoo.

the class ConsumerImpl method closeAsync.

@Override
public CompletableFuture<Void> closeAsync() {
    if (getState() == State.Closing || getState() == State.Closed) {
        batchMessageAckTracker.clear();
        unAckedMessageTracker.close();
        return CompletableFuture.completedFuture(null);
    }
    if (!isConnected()) {
        log.info("[{}] [{}] Closed Consumer (not connected)", topic, subscription);
        setState(State.Closed);
        batchMessageAckTracker.clear();
        unAckedMessageTracker.close();
        client.cleanupConsumer(this);
        return CompletableFuture.completedFuture(null);
    }
    Timeout timeout = stats.getStatTimeout();
    if (timeout != null) {
        timeout.cancel();
    }
    setState(State.Closing);
    long requestId = client.newRequestId();
    ByteBuf cmd = Commands.newCloseConsumer(consumerId, requestId);
    CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    ClientCnx cnx = cnx();
    cnx.sendRequestWithId(cmd, requestId).handle((v, exception) -> {
        cnx.removeConsumer(consumerId);
        if (exception == null || !cnx.ctx().channel().isActive()) {
            log.info("[{}] [{}] Closed consumer", topic, subscription);
            setState(State.Closed);
            batchMessageAckTracker.clear();
            unAckedMessageTracker.close();
            closeFuture.complete(null);
            client.cleanupConsumer(this);
        } else {
            closeFuture.completeExceptionally(exception);
        }
        return null;
    });
    return closeFuture;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Timeout(io.netty.util.Timeout) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

Timeout (io.netty.util.Timeout)30 TimerTask (io.netty.util.TimerTask)26 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 Future (io.netty.util.concurrent.Future)8 FutureListener (io.netty.util.concurrent.FutureListener)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)8 RFuture (org.redisson.api.RFuture)8 AtomicLong (java.util.concurrent.atomic.AtomicLong)6 RedisTimeoutException (org.redisson.client.RedisTimeoutException)5 WriteRedisConnectionException (org.redisson.client.WriteRedisConnectionException)5 ByteBuf (io.netty.buffer.ByteBuf)4 ChannelFuture (io.netty.channel.ChannelFuture)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 ArrayList (java.util.ArrayList)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 RedisAskException (org.redisson.client.RedisAskException)3 RedisException (org.redisson.client.RedisException)3 RedisLoadingException (org.redisson.client.RedisLoadingException)3 RedisMovedException (org.redisson.client.RedisMovedException)3 RedisTryAgainException (org.redisson.client.RedisTryAgainException)3