(旧文整理)Java NIO代码阅读笔记「MappedBuffer」

(过去的学习笔记的归档,所以文风有不同)

这个专栏主要放读JDK的NIO代码实现的一些笔记,不会太系统,也不适合初学者,有基础的同学,有感兴趣的,就跟读好了。对于系统学习NIO,会给大家单开专栏。这个专栏主要使用JDK 1.8的实现:

$ pwd
/Users/weli/projs/jdk1.8

这次想带大家看MappedByteBuffer的实现:

$ find . | grep MappedByteBuffer
./share/classes/java/nio/MappedByteBuffer.java
./solaris/native/java/nio/MappedByteBuffer.c
./windows/native/java/nio/MappedByteBuffer.c

其中MappedByteBuffer.java要依赖几个native methods:

private native boolean isLoaded0(long address, long length, int pageCount);
private native void load0(long address, long length);
private native void force0(FileDescriptor fd, long address, long length);

具体实现看./solaris/native/java/nio/MappedByteBuffer.c

可以看到底层实现都是调用C。接下来重点看到原生平台上面madvisemsync的使用:

关于Linux/UNIX平台的「memory mapping」机制,可以后续细看:

注意原生平台.c代码的话,Java的VM是管不到它的内存的,所以native code一定要做好内存管理的工作,以免造成memory leak:

本篇就到这里。

My Github Page: https://github.com/liweinan

Powered by Jekyll and Theme by solid

If you have any question want to ask or find bugs regarding with my blog posts, please report it here:
https://github.com/liweinan/liweinan.github.io/issues