Netty从入门到精通-伪异步I/O编程

导语
  为了解决BIO面临的一个请求链路需要一个处理线程的问题,然后对其线程模型做了优化,后端通过线程池来对多个客户端请求进行接入处理,形成么客户端M线程池最大线程数N的处理比例关系,但这其中还是M远大于N的操作。但是通过线程池技术可以灵活的调配资源,并且设置线程的最大值,这也就避免了资源被无限制的消耗的问题。
Java面试问题交流群

伪异步线程模型图

在这里插入图片描述

  采用线程池和任务队列的方式可以实现一种被称为是伪异步的I/O通信框架,模型图如上图所示,当有新的客户端接入的时候,将客户端的Socket封装成一个Task任务。然后扔到线程池中进行处理,JDK中的线程池通过维护一个消息队列与多个活跃的线程对消息队列中的任务进行处理。这样因为线程池的大小和队列的大小都是可以设置的,所以所使用的资源也就变成了可控的,这样无论有多少的客户端连接,整个的JVM的资源都不会被消耗完。

  下面我们通过一个小例子来看一下具体的实现是什么样子的。

public class TimeServer {

    public static void main(String[] args) {
        int port = 8080;

        ServerSocket server = null;

        try {
            server = new ServerSocket(port);
            System.out.println("The time server is start in port : "+ port);
            Socket socket = null;
            TimeServerHandlerExecutePool singleExecutor = new TimeServerHandlerExecutePool(50,10000);
            while (true){
                 socket = server.accept();
                 singleExecutor.execute(new TimeServerHandler(socket));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (server!=null){
                System.out.println("The time server close");
                try {
                    server.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                server = null;
            }
        }
    }
}

public class TimeServerHandlerExecutePool {

    private ExecutorService executor;

    public TimeServerHandlerExecutePool(int maxPoolSize,int queueSize){
        executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),maxPoolSize,120L,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(queueSize));

    }
    public void execute(Runnable task){
        executor.execute(task);
    }
}

  客户端的内容与之前博客中的客户端是一样的。所以可以直接使用。

  伪异步I/O通信采用了线程池的方式,来实现服务端连接的处理,这就有效的避免了每次一个客户端连接都建立一个服务端的连接然后创建单独线程去处理,最终导致资源耗尽的问题。但是实际上,伪异步的底层还是通过同步阻塞的方式来进行处理。并没有从根本上解决问题。

  因为在使用线程池的时候只是对对应的连接方式进行了优化处理,通过池化技术对线程创建的多少进行了处理,但是在底层实际操作Task的时候还是同步等待的方式。所以我们依然需要从根本上找到问题,解决问题。

伪异步I/O的弊端

  首先我们先来分析一个InputStream的API。

 /**
     * Reads some number of bytes from the input stream and stores them into
     * the buffer array <code>b</code>. The number of bytes actually read is
     * returned as an integer.  This method blocks until input data is
     * available, end of file is detected, or an exception is thrown.
     *
     * <p> If the length of <code>b</code> is zero, then no bytes are read and
     * <code>0</code> is returned; otherwise, there is an attempt to read at
     * least one byte. If no byte is available because the stream is at the
     * end of the file, the value <code>-1</code> is returned; otherwise, at
     * least one byte is read and stored into <code>b</code>.
     *
     * <p> The first byte read is stored into element <code>b[0]</code>, the
     * next one into <code>b[1]</code>, and so on. The number of bytes read is,
     * at most, equal to the length of <code>b</code>. Let <i>k</i> be the
     * number of bytes actually read; these bytes will be stored in elements
     * <code>b[0]</code> through <code>b[</code><i>k</i><code>-1]</code>,
     * leaving elements <code>b[</code><i>k</i><code>]</code> through
     * <code>b[b.length-1]</code> unaffected.
     *
     * <p> The <code>read(b)</code> method for class <code>InputStream</code>
     * has the same effect as: <pre><code> read(b, 0, b.length) </code></pre>
     *
     * @param      b   the buffer into which the data is read.
     * @return     the total number of bytes read into the buffer, or
     *             <code>-1</code> if there is no more data because the end of
     *             the stream has been reached.
     * @exception  IOException  If the first byte cannot be read for any reason
     * other than the end of the file, if the input stream has been closed, or
     * if some other I/O error occurs.
     * @exception  NullPointerException  if <code>b</code> is <code>null</code>.
     * @see        java.io.InputStream#read(byte[], int, int)
     */
    public int read(byte b[]) throws IOException {
        return read(b, 0, b.length);
    }

  根据描述我们可以知道,在对Socket的输入流进行Read的时候,会一直阻塞下去,直到发生如下的三件事情。

This method blocks until input data is available, end of file is detected, or an exception is thrown
  • 有数据可以读取
  • 可用数据已经读取完了
  • 发生异常的时候

  这就意味着,当对方发送请求或者是应答消息的时候比较慢,或者网络消耗比较严重的时候,读取输入流会被长时间的阻塞。如果发送数据花费了一分钟才发送完成,那么读取的线程也将会在一分钟之后才开始正式读取。如果使用了线程队列,那么其他队列也只能在队列中等待。

  再来看一下OutputStream的API

    /**
     * Writes <code>b.length</code> bytes from the specified byte array
     * to this output stream. The general contract for <code>write(b)</code>
     * is that it should have exactly the same effect as the call
     * <code>write(b, 0, b.length)</code>.
     *
     * @param      b   the data.
     * @exception  IOException  if an I/O error occurs.
     * @see        java.io.OutputStream#write(byte[], int, int)
     */
    public void write(byte b[]) throws IOException {
        write(b, 0, b.length);
    }

  当OutputStream调用write方法写输出流的时候,就会被阻塞,知道发送的字节全部发送完毕之后或者发生异常的时候才会停止。

  TCP/IP协议,当接收方处理较慢的时候,如果不能从TCP的缓冲区中读取数据,这将会导致发送方的TCP Window Size的大小不断的减小。这个时候双方就处于一种Keep-Alive状态,消息发送方将不能在向TCP缓冲区中发送数据,这个时候如果采用的是同步I/O 的方式,write就会无限阻塞,一直到TCP window size大于0 或者发生了IO异常。

  通过对输入流和输出流API文档进行分析,可以知道在API中的读写操作都是阻塞的。而阻塞的时间取决于对方I/O线程的处理速度以及网络传输速度。从本质上来讲,我们是没有办法保证生产环境的网络状况和对应的应用处理速度足够快。如果这样就没有办法保证应用高效执行。

总结

  实际上就像是前面说的那样,伪异步I/O只是对于线程池的优化,并不是从根本上来解决I/O导致线程阻塞的问题。下篇博客我们就来探讨从根本上解决这个问题的方法,以及对应的技术NIO。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nihui123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值