netty Future await方法的实现

Future await
public interface Future<V> extends java.util.concurrent.Future<V> {
    /**
     * Waits for this future to be completed within the
     * specified time limit.
     *
     * @return {@code true} if and only if the future was completed within
     *         the specified time limit
     *
     * @throws InterruptedException
     *         if the current thread was interrupted
     */
    boolean await(long timeoutMillis) throws InterruptedException;
}

future是一个异步消息的返回值,可以调用Future.await(期望等待的时间)来阻塞当线前线,直到future完成,或者期望的时间到期.

这个功能如何实现
  1. 需要阻塞一定时间,到时间没有结果立即返回
  2. 有结果就立即返回

如果让我来实现,我能想到的就是写一个死循环,不断的休眠期望时间的几分之一,休眠结束后,判断是否有结果,如果没有.继续休眠.

        //期望等待时间
        long exceptTime = 10000;
        long start = System.currentTimeMillis();
        while (true){
            //判断是否执行完成,如果执行完成返回
            
            //休眠  exceptTime/10
            Thread.sleep(exceptTime/10);
            //判断是否超过等待时间,如果超过,返回
            if(System.currentTimeMillis()-start>exceptTime){
                return false;
            }
        }
netty DefaultPromise的实现
    private boolean await0(long timeoutNanos, boolean interruptable) throws InterruptedException {
        //如果完成,直接返回
        if (isDone()) {
            return true;
        }
        
        if (timeoutNanos <= 0) {
            return isDone();
        }
        //如果被中断,抛出异常
        if (interruptable && Thread.interrupted()) {
            throw new InterruptedException(toString());
        }

        long startTime = System.nanoTime();
        long waitTime = timeoutNanos;
        boolean interrupted = false;

        try {
            synchronized (this) {
                if (isDone()) {
                    return true;
                }

                if (waitTime <= 0) {
                    return isDone();
                }

                checkDeadLock();
                incWaiters();
                try {
                    for (;;) {
                        try {
                            //调用object的wait方法
                            wait(waitTime / 1000000, (int) (waitTime % 1000000));
                        } catch (InterruptedException e) {
                            if (interruptable) {
                                throw e;
                            } else {
                                interrupted = true;
                            }
                        }

                        if (isDone()) {
                            return true;
                        } else {
                            //等待时间-已经等待的时间,这里应该是interruptable 为false的情况,虽然抛出了中断异常,但还是继续执行下去.
                            waitTime = timeoutNanos - (System.nanoTime() - startTime);
                            if (waitTime <= 0) {
                                return isDone();
                            }
                        }
                    }
                } finally {
                    decWaiters();
                }
            }
        } finally {
            if (interrupted) {
                Thread.currentThread().interrupt();
            }
        }
    }

可以看到主要是调用 Object的wait方法,看来这种需要还是要借助操作系统来实现

object wait方法
public final void wait(long timeout, int nanos) throws InterruptedException

造成当前的线程等待,直到另一个线程为这个object调用notify或notifyAll方法,或者一些其他线程中断(interrupts)当前线程,或者已经过了一定量的时间.
这个方法和一个参数的wait方法是相同的,但是它允许更好的控制时间来在放弃前等待通知,时间用纳秒表示 1000000*timeout+nanos
在其他方面,这个方法和一个参数的wait(long)做一样的事情,尤其是wait(0,0)和wait(0)意味着相同的事情.
当前的线程必须有这个Object的monitor,这个线程释放monitor的所有权等待直到下面的两种情况中的一个发生.

  1. 其它线程通知在这个object的monitor上等待的线程来唤醒,通过notify或notifyAll方法.
  2. 由毫秒+纳秒指定的超时时间已经过去了.
    这个线程等待直到它可能重新获取monitor的所有权,然后执行.
    就像在一个参数版本中,中断和伪唤醒是可能的,这个方法应该总是在循环中使用:
synchronized (obj) {
               while (<condition does not hold>)
                   obj.wait(timeout, nanos);
               ... // Perform action appropriate to condition
           }

这个方法应该被有这个对象monitor的所有权的线程调用.有关线程可以成为监视器所有者的方式的说明,请参阅notify方法.
InterruptedException - 如果任何线程在当前线程等待通知之前或当前线程中断当前线程。 抛出此异常时,将清除当前线程的中断状态。

    public final void wait(long timeout, int nanos) throws InterruptedException {
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
            timeout++;
        }

        wait(timeout);
    }
    
实现思路

获取object锁后,调用 wait 方法进入等待,如果此时任务完成,调用

            if (hasWaiters()) {
                notifyAll();
            }

主要就是调用object 的wait notifyAll实现.

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Netty是一个基于Java的网络编程框架,它提供了高性能、异步事件驱动的网络应用程序开发能力。Netty可以用于构建各种类型的网络应用,包括客户端和服务器端。 要实现基于Netty的P2P代码,可以按照以下步骤进行: 1. 创建一个Server端和一个或多个Client端:首先,你需要创建一个Server端和一个或多个Client端。Server端用于接收来自其他Client端的连接请求,而Client端则用于与其他Client端建立连接。 2. 配置Server端和Client端的Bootstrap:使用Netty的Bootstrap类来配置Server端和Client端的启动参数。你可以设置监听的端口号、线程模型、处理器等。 3. 实现ChannelHandler:在Server端和Client端中,你需要实现自定义的ChannelHandler来处理接收到的消息。ChannelHandler是Netty中用于处理网络事件的组件,你可以在其中编写业务逻辑。 4. 编写消息传输逻辑:在ChannelHandler中,你可以编写消息传输的逻辑。例如,在Server端中,你可以接收来自Client端的消息,并将其转发给其他Client端;在Client端中,你可以发送消息给Server端或其他Client端。 5. 启动Server端和Client端:在代码中调用Server端和Client端的启动方法,启动它们并开始监听连接请求。 6. 进行P2P通信:一旦Server端和Client端都启动成功并建立连接,它们之间就可以进行P2P通信了。你可以通过发送和接收消息来实现点对点的通信。 这只是一个简单的概述,实际的代码实现可能会更加复杂,具体的实现方式还取决于你的需求和设计。你可以参考Netty的官方文档和示例代码来更深入地了解Netty的使用方法

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值