使用 NIO 提升性能

  • 2015-12-28
  • 4,487
  • 0

在nio中和Buffer配合使用的还有Channel。Channel是一个双向通道,既可读,也可写。

Buffer的基本原理

位置(position)、容量(capactiy)、上限(limit)

Buffer的相关操作

1.Buffer的创建

//从堆中分配  
ByteBuffer buffer = ByteBuffer.allocate(1024);  
//直接内存访问  
ByteBuffer buffer = ByteBuffer.allocteDirect(1024);  
//从已有数组中分配  
byte[] bytes = new byte[1024];  
ByteBuffer buffer = ByteBuffer.wrap(bytes);

2.重置和清空缓冲区

rewind()//重读,position=0;mark=-1;  
clear()//重写,position=0;limit=capacity;mark=-1;  
flip()//读写转换,limit=position;position=0;mark=-1;
buffer.compact();//运用于非阻塞io,将position到limit未读完的数据复制到数组头部,并使position位于这段数据的尾部(limit-position),position=limit-position,limit=capacity

3.读写缓冲区

get()
get(byte[] dst)
get(int index)
put(byte b)
put(int index,byte b)
put(byte[] src)

4.标识缓冲区

mark()//mark=position;
reset()//position=mark;

5.复制缓冲区

duplicate()

这个函数对处理复制的Buffer数据很有好处。因为新生的和原缓冲区共享相同的内存数据。并且,对任意一方的数据改动都是可见的,但两者有独立维护了各自的position,limit,mark。

6.缓冲区分片

slice()//position-limit

7.只读缓冲区

asReadOnlyBuffer()

8.文件映射到内存

fileChannel.map(FileChannel.MapMode.READ_WRITE,0,1024);

通道传输标准代码(适用非阻塞io):

public static void channelCopy(ReadableByteChannel src,
                                     WritableByteChannel dest)
            throws IOException {
        ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
        while (src.read(buffer) != -1) {
            // Prepare the buffer to be drained
            buffer.flip();
            // Write to the channel; may block
            dest.write(buffer);
            // If partial transfer, shift remainder down
            // If buffer is empty, same as doing clear( )
            buffer.compact();
        }
        // EOF will leave buffer in fill state
        buffer.flip();
        // Make sure that the buffer is fully drained
        while (buffer.hasRemaining()) {
            dest.write(buffer);
        }
}
>> 转载请注明来源:使用 NIO 提升性能

评论

还没有任何评论,你来说两句吧

发表评论