转: mmap文件映射内存分析

2/22/2017来源:ASP.NET技巧人气:1270

http://edisonlz.iteye.com/blog/1197453

http://blog.yufeng.info/archives/2456

主要是了解mac下vmmap命令配合使用情况,mmap内存映射对应java nio的RandomaccessFile的FileChannel进行map()操作。

public class RandomMapFileReadTest { static int length = 0x8000000; // 128 Mb public static void main(String[] args) throws FileNotFoundException { try{ // 为了以可读可写的方式打开文件,这里使用RandomAccessFile来创建文件。 FileChannel fc = new RandomAccessFile("test.dat", "rw").getChannel(); //注意,文件通道的可读可写要建立在文件流本身可读写的基础之上 MappedByteBuffer out = fc.map(FileChannel.MapMode.READ_WRITE, 0, length); //写128M的内容 byte[] readArray = new byte[1024]; for (int i = 0; i < length; i++) { byte byteChar = out.get(); readArray[i%1024] = byteChar; if(i == length/2) { Thread.sleep(20); System.out.PRintln("read half..."); } } // System.out.println("Finished writing"); //读取文件中间6个字节内容 System.out.println("Finished getting " + readArray.length); fc.close(); }catch (Exception e) { e.printStackTrace(); } } }

一个已经存在的128M文件,在map后,通过for循环不断读入内存,可以通过

vmmap -resident <pid>

命令看出,map的resident内存是一步一步读入的:

yangyamin:~ yangyamin$ vmmap -resident 1486 | grep test mapped file 0000000115a8d000-000000011da8d000 [128.0M 56.9M] rw-/rwx SM=PRV /Users/yangyamin/data/spv/test.dat yangyamin:~ yangyamin$ vmmap -resident 1486 | grep test mapped file 0000000115a8d000-000000011da8d000 [128.0M 89.7M] rw-/rwx SM=PRV /Users/yangyamin/data/spv/test.dat yangyamin:~ yangyamin$ vmmap -resident 1486 | grep test \mapped file 0000000115a8d000-000000011da8d000 [128.0M 107.5M] rw-/rwx SM=PRV /Users/yangyamin/data/spv/test.dat yangyamin:~ yangyamin$ vmmap -resident 1486 | grep test mapped file 0000000115a8d000-000000011da8d000 [128.0M 125.9M] rw-/rwx SM=PRV /Users/yangyamin/data/spv/test.dat yangyamin:~ yangyamin$ vmmap -resident 1486 | grep test mapped file 0000000115a8d000-000000011da8d000 [128.0M 128.0M] rw-/rwx SM=PRV /Users/yangyamin/data/spv/test.dat yangyamin:~ yangyamin$ vmmap -resident 1486 | grep test mapped file 0000000115a8d000-000000011da8d000 [128.0M 128.0M] rw-/rwx SM=PRV /Users/yangyamin/data/spv/test.dat