深刻浅出NIO之Channel、Buffer

前言

Java NIO 由如下几个核心部分组成: 数组

1 、Buffer缓存

二、Channel app

三、Selectordom

传统的IO操做面向数据流,意味着每次从流中读一个或多个字节,直至完成,数据没有被缓存在任何地方。异步

NIO操做面向缓冲区,数据从Channel读取到Buffer缓冲区,随后在Buffer中处理数据。jvm

本文着重介绍Channel和Buffer的概念以及在文件读写方面的应用和内部实现原理。socket

Buffer

A buffer is a linear, finite sequence of elements of a specific primitive type.this

一块缓存区,内部使用字节数组存储数据,并维护几个特殊变量,实现数据的反复利用。 spa

一、mark:初始值为-1,用于备份当前的position; code

二、position:初始值为0,position表示当前能够写入或读取数据的位置,当写入或读取一个数据后,position向前移动到下一个位置; 

三、limit:写模式下,limit表示最多能往Buffer里写多少数据,等于capacity值;读模式下,limit表示最多能够读取多少数据。 

四、capacity:缓存数组大小

mark():把当前的position赋值给mark

 
  1. public final Buffer mark() {

  2.    mark = position;

  3.    return this;

  4. }

reset():把mark值还原给position

 
  1. public final Buffer reset() {

  2.    int m = mark;

  3.    if (m < 0)

  4.        throw new InvalidMarkException();

  5.    position = m;

  6.    return this;

  7. }

clear():一旦读完Buffer中的数据,须要让Buffer准备好再次被写入,clear会恢复状态值,但不会擦除数据。

 
  1. public final Buffer clear() {

  2.    position = 0;

  3.    limit = capacity;

  4.    mark = -1;

  5.    return this;

  6. }

flip():Buffer有两种模式,写模式和读模式,flip后Buffer从写模式变成读模式。

 
  1. public final Buffer flip() {

  2.    limit = position;

  3.    position = 0;

  4.    mark = -1;

  5.    return this;

  6. }

rewind():重置position为0,从头读写数据。

 
  1. public final Buffer rewind() {

  2.    position = 0;

  3.    mark = -1;

  4.    return this;

  5. }

目前Buffer的实现类有如下几种:

  • ByteBuffer

  • CharBuffer

  • DoubleBuffer

  • FloatBuffer

  • IntBuffer

  • LongBuffer

  • ShortBuffer

  • MappedByteBuffer

ByteBuffer

A byte buffer,extend from Buffer

ByteBuffer的实现类包括"HeapByteBuffer"和"DirectByteBuffer"两种。

HeapByteBuffer

 
  1. public static ByteBuffer allocate(int capacity) {

  2.    if (capacity < 0)

  3.        throw new IllegalArgumentException();

  4.    return new HeapByteBuffer(capacity, capacity);

  5. }

  6. HeapByteBuffer(int cap, int lim) {  

  7.    super(-1, 0, lim, cap, new byte[cap], 0);

  8. }

HeapByteBuffer经过初始化字节数组hd,在虚拟机堆上申请内存空间。

DirectByteBuffer

 
  1. public static ByteBuffer allocateDirect(int capacity) {

  2.    return new DirectByteBuffer(capacity);

  3. }

  4. DirectByteBuffer(int cap) {

  5.    super(-1, 0, cap, cap);

  6.    boolean pa = VM.isDirectMemoryPageAligned();

  7.    int ps = Bits.pageSize();

  8.    long size = Math.max(1L, (long)cap + (pa ? ps : 0));

  9.    Bits.reserveMemory(size, cap);

  10.  

  11.    long base = 0;

  12.    try {

  13.        base = unsafe.allocateMemory(size);

  14.    } catch (OutOfMemoryError x) {

  15.        Bits.unreserveMemory(size, cap);

  16.        throw x;

  17.    }

  18.    unsafe.setMemory(base, size, (byte) 0);

  19.    if (pa && (base % ps != 0)) {

  20.        // Round up to page boundary

  21.        address = base + ps - (base & (ps - 1));

  22.    } else {

  23.        address = base;

  24.    }

  25.    cleaner = Cleaner.create(this, new Deallocator(base, size, cap));

  26.    att = null;

  27. }

DirectByteBuffer经过unsafe.allocateMemory在物理内存中申请地址空间(非jvm堆内存),并在ByteBuffer的address变量中维护指向该内存的地址。 unsafe.setMemory(base, size, (byte) 0)方法把新申请的内存数据清零。

Channel

A channel represents an open connection to an entity such as a hardware device, a file, a network socket, or a program component that is capable of performing one or more distinct I/O operations, for example reading or writing.

NIO把它支持的I/O对象抽象为Channel,Channel又称“通道”,相似于原I/O中的流(Stream),但有所区别: 

一、流是单向的,通道是双向的,可读可写。 

二、流读写是阻塞的,通道能够异步读写。 

三、流中的数据能够选择性的先读到缓存中,通道的数据老是要先读到一个缓存中,或从缓存中写入,以下所示:

目前已知Channel的实现类有:

  • FileChannel

  • DatagramChannel

  • SocketChannel

  • ServerSocketChannel

FileChannel

A channel for reading, writing, mapping, and manipulating a file. 一个用来写、读、映射和操做文件的通道。

FileChannel的read、write和map经过其实现类FileChannelImpl实现。

read实现

 
  1. public int read(ByteBuffer dst) throws IOException {

  2.    ensureOpen();

  3.    if (!readable)

  4.        throw new NonReadableChannelException();

  5.    synchronized (positionLock) {

  6.        int n = 0;

  7.        int ti = -1;

  8.        try {

  9.            begin();

  10.            ti = threads.add();

  11.            if (!isOpen())

  12.                return 0;

  13.            do {

  14.                n = IOUtil.read(fd, dst, -1, nd);

  15.            } while ((n == IOStatus.INTERRUPTED) && isOpen());

  16.            return IOStatus.normalize(n);

  17.        } finally {

  18.            threads.remove(ti);

  19.            end(n > 0);

  20.            assert IOStatus.check(n);

  21.        }

  22.    }

  23. }

FileChannelImpl的read方法经过IOUtil的read实现:

 
  1. static int read(FileDescriptor fd, ByteBuffer dst, long position,

  2.                NativeDispatcher nd) IOException {

  3.    if (dst.isReadOnly())

  4.        throw new IllegalArgumentException("Read-only buffer");

  5.    if (dst instanceof DirectBuffer)

  6.        return readIntoNativeBuffer(fd, dst, position, nd);

  7.  

  8.    // Substitute a native buffer

  9.    ByteBuffer bb = Util.getTemporaryDirectBuffer(dst.remaining());

  10.    try {

  11.        int n = readIntoNativeBuffer(fd, bb, position, nd);

  12.        bb.flip();

  13.        if (n > 0)

  14.            dst.put(bb);

  15.        return n;

  16.    } finally {

  17.        Util.offerFirstTemporaryDirectBuffer(bb);

  18.    }

  19. }

经过上述实现能够看出,基于channel的文件数据读取步骤以下: 

一、申请一块和缓存同大小的DirectByteBuffer bb。 

二、读取数据到缓存bb,底层由NativeDispatcher的read实现。 

三、把bb的数据读取到dst(用户定义的缓存,在jvm中分配内存)。 

read方法致使数据复制了两次

write实现

 
  1. public int write(ByteBuffer src) throws IOException {

  2.    ensureOpen();

  3.    if (!writable)

  4.        throw new NonWritableChannelException();

  5.    synchronized (positionLock) {

  6.        int n = 0;

  7.        int ti = -1;

  8.        try {

  9.            begin();

  10.            ti = threads.add();

  11.            if (!isOpen())

  12.                return 0;

  13.            do {

  14.                n = IOUtil.write(fd, src, -1, nd);

  15.            } while ((n == IOStatus.INTERRUPTED) && isOpen());

  16.            return IOStatus.normalize(n);

  17.        } finally {

  18.            threads.remove(ti);

  19.            end(n > 0);

  20.            assert IOStatus.check(n);

  21.        }

  22.    }

  23. }

和read实现同样,FileChannelImpl的write方法经过IOUtil的write实现:

 
  1. static int write(FileDescriptor fd, ByteBuffer src, long position,

  2.                 NativeDispatcher nd) throws IOException {

  3.    if (src instanceof DirectBuffer)

  4.        return writeFromNativeBuffer(fd, src, position, nd);

  5.    // Substitute a native buffer

  6.    int pos = src.position();

  7.    int lim = src.limit();

  8.    assert (pos <= lim);

  9.    int rem = (pos <= lim ? lim - pos : 0);

  10.    ByteBuffer bb = Util.getTemporaryDirectBuffer(rem);

  11.    try {

  12.        bb.put(src);

  13.        bb.flip();

  14.        // Do not update src until we see how many bytes were written

  15.        src.position(pos);

  16.        int n = writeFromNativeBuffer(fd, bb, position, nd);

  17.        if (n > 0) {

  18.            // now update src

  19.            src.position(pos + n);

  20.        }

  21.        return n;

  22.    } finally {

  23.        Util.offerFirstTemporaryDirectBuffer(bb);

  24.    }

  25. }

经过上述实现能够看出,基于channel的文件数据写入步骤以下: 

一、申请一块DirectByteBuffer,bb大小为byteBuffer中的limit - position。 

二、复制byteBuffer中的数据到bb中。 

三、把数据从bb中写入到文件,底层由NativeDispatcher的write实现,具体以下:

 
  1. private static int writeFromNativeBuffer(FileDescriptor fd,

  2.        ByteBuffer bb, long position, NativeDispatcher nd)

  3.    throws IOException {

  4.    int pos = bb.position();

  5.    int lim = bb.limit();

  6.    assert (pos <= lim);

  7.    int rem = (pos <= lim ? lim - pos : 0);

  8.  

  9.    int written = 0;

  10.    if (rem == 0)

  11.        return 0;

  12.    if (position != -1) {

  13.        written = nd.pwrite(fd,

  14.                            ((DirectBuffer)bb).address() + pos,

  15.                            rem, position);

  16.    } else {

  17.        written = nd.write(fd, ((DirectBuffer)bb).address() + pos, rem);

  18.    }

  19.    if (written > 0)

  20.        bb.position(pos + written);

  21.    return written;

  22. }

write方法也致使了数据复制了两次

Channel和Buffer示例

 
  1. File file = new RandomAccessFile("data.txt", "rw");

  2. FileChannel channel = file.getChannel();

  3. ByteBuffer buffer = ByteBuffer.allocate(48);

  4.  

  5. int bytesRead = channel.read(buffer);

  6. while (bytesRead != -1) {

  7.    System.out.println("Read " + bytesRead);

  8.    buffer.flip();

  9.    while(buffer.hasRemaining()){

  10.        System.out.print((char) buffer.get());

  11.    }

  12.    buffer.clear();

  13.    bytesRead = channel.read(buffer);

  14. }

  15. file.close();

注意buffer.flip() 的调用,首先将数据写入到buffer,而后变成读模式,再从buffer中读取数据。

总结

经过本文的介绍,但愿你们对Channel和Buffer在文件读写方面的应用和内部实现有了必定了解,努力作到不被一叶障目。

相关文章
相关标签/搜索