Search in sources :

Example 26 with TimerTask

use of io.netty.util.TimerTask 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 27 with TimerTask

use of io.netty.util.TimerTask 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 28 with TimerTask

use of io.netty.util.TimerTask in project openflowplugin by opendaylight.

the class RoleContextImpl method sendRoleChangeToDevice.

private ListenableFuture<RpcResult<SetRoleOutput>> sendRoleChangeToDevice(final OfpRole newRole) {
    final Boolean isEqualRole = config.isEnableEqualRole();
    if (isEqualRole) {
        LOG.warn("Skip sending role change request to device {} as user enabled" + " equal role for controller", deviceInfo);
        return Futures.immediateFuture(null);
    }
    LOG.debug("Sending new role {} to device {}", newRole, deviceInfo);
    if (deviceInfo.getVersion() >= OFConstants.OFP_VERSION_1_3) {
        final SetRoleInput setRoleInput = new SetRoleInputBuilder().setControllerRole(newRole).setNode(new NodeRef(deviceInfo.getNodeInstanceIdentifier())).build();
        final Future<RpcResult<SetRoleOutput>> setRoleOutputFuture = roleService.setRole(setRoleInput);
        final TimerTask timerTask = timeout -> {
            if (!setRoleOutputFuture.isDone()) {
                LOG.warn("New role {} was not propagated to device {} during {} sec", newRole, deviceInfo, SET_ROLE_TIMEOUT);
                setRoleOutputFuture.cancel(true);
            }
        };
        timer.newTimeout(timerTask, SET_ROLE_TIMEOUT, TimeUnit.MILLISECONDS);
        return JdkFutureAdapters.listenInPoolThread(setRoleOutputFuture);
    }
    LOG.info("Device: {} with version: {} does not support role {}", deviceInfo, deviceInfo.getVersion(), newRole);
    return Futures.immediateFuture(null);
}
Also used : MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) RpcResult(org.opendaylight.yangtools.yang.common.RpcResult) SetRoleInput(org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInput) LoggerFactory(org.slf4j.LoggerFactory) OfpRole(org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole) JdkFutureAdapters(com.google.common.util.concurrent.JdkFutureAdapters) AtomicReference(java.util.concurrent.atomic.AtomicReference) ContextChainMastershipWatcher(org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainMastershipWatcher) HashSet(java.util.HashSet) ServiceGroupIdentifier(org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier) Future(java.util.concurrent.Future) RequestContextUtil(org.opendaylight.openflowplugin.impl.services.util.RequestContextUtil) OpenflowProviderConfig(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.provider.config.rev160510.OpenflowProviderConfig) TimerTask(io.netty.util.TimerTask) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) NodeRef(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef) Timeout(io.netty.util.Timeout) Logger(org.slf4j.Logger) RoleContext(org.opendaylight.openflowplugin.api.openflow.role.RoleContext) CancellationException(java.util.concurrent.CancellationException) ContextChainMastershipState(org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainMastershipState) AbstractRequestContext(org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext) SalRoleService(org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SalRoleService) Collection(java.util.Collection) SetRoleInputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInputBuilder) FutureCallback(com.google.common.util.concurrent.FutureCallback) SetRoleOutput(org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleOutput) OFConstants(org.opendaylight.openflowplugin.api.OFConstants) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) DeviceInfo(org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo) Futures(com.google.common.util.concurrent.Futures) HashedWheelTimer(io.netty.util.HashedWheelTimer) RequestContext(org.opendaylight.openflowplugin.api.openflow.device.RequestContext) NodeRef(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef) SetRoleInputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInputBuilder) TimerTask(io.netty.util.TimerTask) RpcResult(org.opendaylight.yangtools.yang.common.RpcResult) SetRoleInput(org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInput)

Example 29 with TimerTask

use of io.netty.util.TimerTask in project web3sdk by FISCO-BCOS.

the class Service method asyncSendChannelMessage2.

public void asyncSendChannelMessage2(ChannelRequest request, ChannelResponseCallback2 callback) {
    try {
        logger.debug("处理链上链下请求: " + request.getMessageID());
        callback.setService(this);
        ChannelMessage2 channelMessage = new ChannelMessage2();
        channelMessage.setSeq(request.getMessageID());
        channelMessage.setResult(0);
        // 链上链下请求0x30
        channelMessage.setType((short) 0x30);
        channelMessage.setData(request.getContent().getBytes());
        channelMessage.setTopic(request.getToTopic());
        try {
            List<ConnectionInfo> fromConnectionInfos = new ArrayList<ConnectionInfo>();
            // 设置发送节点
            ChannelConnections fromChannelConnections = allChannelConnections.get(orgID);
            if (fromChannelConnections == null) {
                // 没有找到对应的链
                // 返回错误
                logger.error("没有找到本机构:{}", orgID);
                throw new Exception("未找到本机构");
            }
            fromConnectionInfos.addAll(fromChannelConnections.getConnections());
            logger.debug("发送机构:{} 节点数:{}", request.getFromOrg(), fromChannelConnections.getConnections().size());
            callback.setFromChannelConnections(fromChannelConnections);
            callback.setFromConnectionInfos(fromConnectionInfos);
            // 设置消息内容
            callback.setRequest(channelMessage);
            seq2Callback.put(request.getMessageID(), callback);
            if (request.getTimeout() > 0) {
                final ChannelResponseCallback2 callbackInner = callback;
                callback.setTimeout(timeoutHandler.newTimeout(new TimerTask() {

                    ChannelResponseCallback2 _callback = callbackInner;

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        // 处理超时逻辑
                        _callback.onTimeout();
                    }
                }, request.getTimeout(), TimeUnit.MILLISECONDS));
            }
            callback.retrySendMessage();
        } catch (Exception e) {
            logger.error("发送消息异常 消息未发出", e);
            ChannelResponse response = new ChannelResponse();
            response.setErrorCode(100);
            response.setMessageID(request.getMessageID());
            response.setErrorMessage(e.getMessage());
            response.setContent("");
            callback.onResponse(response);
            return;
        }
    } catch (Exception e) {
        logger.error("系统错误", e);
    }
}
Also used : ChannelConnections(org.bcos.channel.handler.ChannelConnections) ChannelMessage2(org.bcos.channel.dto.ChannelMessage2) TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) ArrayList(java.util.ArrayList) ConnectionInfo(org.bcos.channel.handler.ConnectionInfo) ChannelResponse(org.bcos.channel.dto.ChannelResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 30 with TimerTask

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

the class RedissonCountDownLatch method await.

private CompletableFuture<Boolean> await(AtomicLong time, RedissonCountDownLatchEntry entry) {
    if (time.get() <= 0) {
        unsubscribe(entry);
        return CompletableFuture.completedFuture(false);
    }
    long curr = System.currentTimeMillis();
    CompletableFuture<Long> countFuture = getCountAsync().toCompletableFuture();
    return countFuture.whenComplete((r, e) -> {
        if (e != null) {
            unsubscribe(entry);
        }
    }).thenCompose(r -> {
        if (r == 0) {
            unsubscribe(entry);
            return CompletableFuture.completedFuture(true);
        }
        long el = System.currentTimeMillis() - curr;
        time.addAndGet(-el);
        if (time.get() <= 0) {
            unsubscribe(entry);
            return CompletableFuture.completedFuture(false);
        }
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        long current = System.currentTimeMillis();
        AtomicBoolean executed = new AtomicBoolean();
        AtomicReference<Timeout> futureRef = new AtomicReference<>();
        Runnable listener = () -> {
            executed.set(true);
            if (futureRef.get() != null) {
                futureRef.get().cancel();
            }
            long elapsed = System.currentTimeMillis() - current;
            time.addAndGet(-elapsed);
            commandExecutor.transfer(await(time, entry), future);
        };
        entry.addListener(listener);
        if (!executed.get()) {
            Timeout timeoutFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {

                @Override
                public void run(Timeout timeout) throws Exception {
                    if (entry.removeListener(listener)) {
                        long elapsed = System.currentTimeMillis() - current;
                        time.addAndGet(-elapsed);
                        commandExecutor.transfer(await(time, entry), future);
                    }
                }
            }, time.get(), TimeUnit.MILLISECONDS);
            futureRef.set(timeoutFuture);
        }
        return future;
    });
}
Also used : Timeout(io.netty.util.Timeout) LongCodec(org.redisson.client.codec.LongCodec) CommandAsyncExecutor(org.redisson.command.CommandAsyncExecutor) Arrays(java.util.Arrays) java.util.concurrent(java.util.concurrent) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CountDownLatchPubSub(org.redisson.pubsub.CountDownLatchPubSub) AtomicReference(java.util.concurrent.atomic.AtomicReference) RedisCommands(org.redisson.client.protocol.RedisCommands) RFuture(org.redisson.api.RFuture) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) AtomicLong(java.util.concurrent.atomic.AtomicLong) RCountDownLatch(org.redisson.api.RCountDownLatch) TimerTask(io.netty.util.TimerTask) 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) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Aggregations

Timeout (io.netty.util.Timeout)38 TimerTask (io.netty.util.TimerTask)38 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)11 AtomicLong (java.util.concurrent.atomic.AtomicLong)8 RFuture (org.redisson.api.RFuture)8 RedisTimeoutException (org.redisson.client.RedisTimeoutException)7 FutureListener (io.netty.util.concurrent.FutureListener)6 ByteBuf (io.netty.buffer.ByteBuf)5 ChannelFuture (io.netty.channel.ChannelFuture)5 Future (io.netty.util.concurrent.Future)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 ArrayList (java.util.ArrayList)5 RedisException (org.redisson.client.RedisException)5 WriteRedisConnectionException (org.redisson.client.WriteRedisConnectionException)5 CompletableFutureWrapper (org.redisson.misc.CompletableFutureWrapper)5 RedisConnection (org.redisson.client.RedisConnection)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 ChannelFutureListener (io.netty.channel.ChannelFutureListener)3 IOException (java.io.IOException)3