Nio 是一种非阻塞io模型,在java1.4引入
Buffer 缓存区 在nio中,所有数组都是通过缓冲区进行处理的 bytebuffer 除了直接内存开辟,底层都是使用了byte[] 作为媒介 几个重要的概念 容量 (capacity) :表示 Buffer 最大数据容量,缓冲区容量不能为负,并且创建后不能更改。 限制 (limit) :第一个不应该读取的数据的索引,即位于 limit 后的数据不可读。缓冲区的限制不能为负,并且不能大于其容量。 位置 (position):下一个要读取或写入的数据的索引。缓冲区的位置不能为负,并且不能大于其限制 标记 (mark) 与重置 (reset) :标记是一个索引,通过 Buffer 中的 mark() 方法指定 Buffer 中一个特定的 position,之后可以通过调用 reset() 方法恢复到这个 position. 代码 创建一个1024大小的缓冲区
ByteBuffer allocate = ByteBuffer . allocate ( 1024 ) ;
向缓冲区添加数据, 我们可以向缓存区中添加不同类型的数组,nio已经做好了封装
allocate. putLong ( 1 ) ;
allocate. putInt ( 2 ) ;
allocate. putDouble ( 1.2 ) ;
allocate. flip ( ) ;
long aLong = allocate. getLong ( ) ;
System . out. println ( aLong) ;
allocate. mark ( ) ;
long aLong = allocate. getLong ( ) ;
int anInt = allocate. getInt ( ) ;
System . out. println ( aLong) ;
System . out. println ( anInt) ;
allocate. reset ( ) ;
long aLong1 = allocate. getLong ( ) ;
System . out. println ( aLong1) ;
堆外内存
buffer 中提供了一个很重要的功能,可以让我们直接开辟物理内存,相当于c 语言的 malloc
ByteBuffer bytebuffer = ByteBuffer . allocateDirect ( 1024 ) ;