NIO是啥?
NIO是Java从JDK1.4开始引入的一系列改进版输入输出处理手段,也就是New IO,简称NIO,也有说法叫NonBlocking IO,是同步非阻塞式的IO模型,准确地说它支持阻塞非阻塞两种模式。
本篇主要介绍NIO提供的三大组件的概念及使用:Buffer,Channel,Selector。
Buffer
Buffer可以理解为是一个容器,用于存储数据,本质是个数组,存储的元素类型是基本类型。
无论是发送还是读取Channel中的数据,都必须先置入Buffer。
java.nio.Buffer是一个抽象类,子类包括有除boolean外其他所有基本类型的XxBuffer,最常用的是ByteBuffer。
Buffer中的重要概念
capacity:缓冲区的容量,表示该Buffer的最大数据容量,即最多可以存储多少数据。
limit:限制位,标记position能够到达的最大位置,默认为缓冲区最后一位。
position:操作位,指向即将操作位置,默认指向0。
mark:可选标记位。默认不启用,Buffer允许直接将position定位到mark处。
他们满足的关系:mark <= position <= limit <= capacity
以ByteBuffer.allocate(capacity)为例,说明几个重要的过程:
-
初始化创建HeapByteBuffer,mark = -1,position = 0,limit = cap。
-
通过put方法向Buffer中加入数据,position++。
-
装入数据结束后,调用flip方法,将limit设置为position所在位置,position置为0,表示[position,limit]这段需要开始进行输出了【可以使用get方法读取数据】。
-
输出结束后,调用clear方法,将position置为0,limit置为cap,为下一次读取数据做好准备。
Buffer的所有子类都提供了put和get方法,对应向Buffer存入数据和从Buffe中取出数据,方式分为以下两种:
-
相对:从Buffer的当前pos处开始读取或写入数据,然后将pos的值按处理元素的个数增加。
-
绝对:直接根据索引向Buffer中读取或写入数据,不会影响pos位置本身的值。
Buffer使用Demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
常用方法介绍
其实Buffer操作的逻辑比较简单,每个方法操作的字段也不外乎上面介绍的几个,下面是一些常用的方法:
设置方法
-
Buffer position(newPosition): 将pos设置为newPosition。
-
Buffer limit(newLimit):将limit设置为newLimit。
数据操作
-
Buffer reset:将pos置为mark的位置。
-
Buffer rewind:将pos置为0,取消设置的mark。
-
Buffer flip: 将limit置pos位置,pos置0。
-
Buffer clear:将position置为0,limit置为cap。
其他操作
1 2 3 4 5 6 7 8 9 |
|
Channel
Channel概述
Channel 类似于传统的流对象,但有些不同:
-
Channel 直接将指定文件的部分或全部直接映射 Buffer。
-
程序不能直接访 Channel 中的数据,包括读取、写入都不行,Channel只能与 Buffer 进行交互。意思是,程序要读数据时需要先通过Buffer从Channel中获取数据,然后从Buffer中读取数据。
-
Channel通常可以异步读写,但默认是阻塞的,需要手动设置为非阻塞。
Channel不应该通过构造器来直接创建,而是通过传统的节点InputStream、OutputStream的getChannel()方法来返回对应的Channel,或者通过RandomAccessFile对象的getChannel方法。
Channel中最常用的三种方法:
-
map():将Channel对应的部分或全部数据映射成ByteBuffer。
-
read():从Buffer中读取数据。
-
write():向Buffer中写入数据。
RandomAccessFile#getChannel
下面是个简单的示例,通过RandomAccessFile的getChannel方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
SocketChannel与ServerSocketChannel
Java为Channel接口根据不同功能,提供了不同的实现类,比如我们下面的示例:支持TCP网络通信的SocketChannel和ServerSocketChannel。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
|
Selector
NIO实现非阻塞IO的其中关键组件之一就是Selector多路复用选择器,可以注册多个Channel到一个Selector中。Selector可以不断执行select操作,判断这些注册的Channel是否有已就绪的IO事件,如可读,可写,网络连接已完成等。
一个线程通过使用一个Selector管理多个Channel。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
|
想要了解更多可以私信小编哦!