深刻淺出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在文件讀寫方面的應用和內部實現有了必定了解,努力作到不被一葉障目。

相關文章
相關標籤/搜索