java.nio.DirectByteBuffer探秘【持续更新,更新完后放出】

最近看到Chronicle号称写文件非常快,用了这种类

map0 = new MappedMemory(fileChannel.map(FileChannel.MapMode.READ_WRITEindex * blockSizeblockSize + overlapSize), index);

 

fileChannel.map函数说明见下方

MappedByteBuffer java.nio.channels.FileChannel.map(MapMode mode, long position, long size) throws IOException
说明返回的值为java.nio.MappedByteBuffer

 

关于MappedByteBuffer的类说明如下:

 

java.nio.MappedByteBuffer



A direct byte buffer whose content is a memory-mapped region of a file.

Mapped byte buffers are created via the FileChannel.map method. This class extends the ByteBuffer class with operations that are specific to memory-mapped file regions.

A mapped byte buffer and the file mapping that it represents remain valid until the buffer itself is garbage-collected.

The content of a mapped byte buffer can change at any time, for example if the content of the corresponding region of the mapped file is changed by this program or another. Whether or not such changes occur, and when they occur, is operating-system dependent and therefore unspecified.

All or part of a mapped byte buffer may become inaccessible at any time, for example if the mapped file is truncated. An attempt to access an inaccessible region of a mapped byte buffer will not change the buffer's content and will cause an unspecified exception to be thrown either at the time of the access or at some later time. It is therefore strongly recommended that appropriate precautions be taken to avoid the manipulation of a mapped file by this program, or by a concurrently running program, except to read or write the file's content.

Mapped byte buffers otherwise behave no differently than ordinary direct byte buffers.

  • Since:

  • 1.4

  • Author:

  • Mark Reinhold

  • JSR-51 Expert Group

     

    在此处,因为fileChannel 的实际类型为RandomAccessFile,所以返回的实际为DirectByteBuffer.

     

    具体的类继承关系如下:

    java.nio.DirectByteBuffer探秘【持续更新,更新完后放出】

=================================华丽的分隔线

关于回收的方法

private static void unmap(MappedByteBuffer bb) {

        Cleaner cl = ((DirectBuffer) bb).cleaner();

        if (cl != null)

            cl.clean();

    }

 关于从MappedBuffer获取内存地址的方法

public long address() {

        return ((DirectBuffer) buffer).address();

    }

后面就可以通过UnSafe来直接操作这个字段。

 

 

 

你可能感兴趣的:(Chronicle)