理解AsynchronousChannelGroup

简单说来,在AIO中,操作系统为我们做了更多的事情。因为操作系统更底层,所以理论上来讲效率会更高些。

 

AsynchronousChannelGroup可以理解为一个JVM中对于Socket相关操作的一些公共资源的代表。

 

一个ChannelGroup和一个(或2个)thread pool关联。

 

理解AsynchronousChannelGroup 

首先引用PRO JAVA 7 NIO2书中的一段话,来解释一下AsynchronousChannelGroup的几个关键点。

 写道
the asynchronous API introduces a class named AsynchronousChannelGroup, which presents the concept of an asynchronous channel group , in which each asynchronous channel belongs to a channel group (the default one or a specified one) that shares a pool of Java threads. These threads receive instruct ions to perform I/O events and they dispatch the results to the completion handlers. The asynchronous channel group encapsulat es thread pool and the resources shared by all the threads working for the channels. Also, the channel is in effect owned by the group, so if the group is closed, the channel is closed too.

 

首先,每一个asynchronous channel都属于同一个group,共享一个Java线程池

 

1. 从代码创建角度来看无论是AsynchronousServerSocketChannel还是AsynchronousSocketChannel的创建都使用各自的静态方法open,而open方法便需要asynchronousChannelGroup。

 

2. 可以发现AsynchronousChannelGroup其内部其实是一个(一些)线程池来进行实质工作的;而他们干的活就是等待IO事件,处理数据,分发各个注册的completion handlers

 

其次便是NIO与NIO2的区别了

即REACTOR PROACTOR,同步IO和异步IO

 

在同步IO中等待IO事件由我们注册的selector来完成,在感兴趣的事情来了,我们的线程来accept.read.write.connect...干活,干好后再交由业务逻辑处理。

 

在异步IO中等待IO事件同样为acceptor,read,write,connect,但数据处理交由系统完成,我们需要做的就是在completion handlers中处理业务逻辑。

 

谁来干以前的活

 

是时候来想想NIO中(最朴素的),我们通常要干两件比较底层的事情

 

1. 弄一个seletor,在他身上注册各种感兴趣的事件,然后select,等待感兴趣的事情发生

 

2. 感兴趣的事情发生了,比如可以读了,这时便需要我们的线程从channel中读数据到bytebuffer里

 

那么在AIO里,这些都不需要了,因为系统替你做好了!

 

但是,系统替你做的事是2,系统级的AIO,windows下的iocp(真AIO),linux下的epoll(模拟)

 

那1这个事情其实还是要由java的线程去做,所以我们还是需要一个类似seletor的存在,他就是我们提供的AsynchronousChannelGroup中的线程池。

 

 

下篇中将详细讲述AsynchronousChannelGroup的创建及各自的特点。http://dongxuan.iteye.com/blog/1345049

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值