一、Buffer 的基本用法:

  1. Write data into the Buffer
  2. Call buffer.flip()
  3. Read data out of the Buffer
  4. Call buffer.clear() or buffer.compact()NIO: (一)Buffer的理解
二、Buffer 的常用方法:
1. ByteBuffer.allocate(48);   ----->  java.nio.HeapByteBuffer[pos=0 lim=48 cap=48]
分配的是堆上内存,GC可以直接回收。

NIO: (一)Buffer的理解

2. ByteBuffer.allocateDirect(48);  -----> java.nio.DirectByteBuffer[pos=0 lim=48 cap=48]
分配的是堆外内存,即操作系统的直接内存,buffer的内存区域不受GC管理。
但jdk做了封装,他关联了一个Cleaner对象,在回收cleaner 对象时,会申请操作系统来回收这块内存区域。
也就是说,内存的回收也不需要我们手动管理了!

NIO: (一)Buffer的理解

3. clear() and compact() 
clear(): 转为写模式,position置为0;
compact():  转为写模式,compact()将所有未读数据复制到开头Buffer。然后它position在最后一个未读元素之后设置。该limit仍然设置为capacity,就像clear()那样。现在Buffer已准备好写入,但您不会覆盖未读数据。
    public final Buffer clear() {
        position = 0;
        limit = capacity;
        mark = -1;
        return this;
    }
    public ByteBuffer compact() {

        System.arraycopy(hb, ix(position()), hb, ix(0), remaining());
        position(remaining());
        limit(capacity());
        discardMark();
        return this;

    }

compact(): 未读完数据,被保留。可以在写后,继续读取,clear()会覆盖。

参考: http://tutorials.jenkov.com/java-nio/buffers.html#clear

相关文章: