轉: mmap檔案對映記憶體分析
阿新 • • 發佈:2019-01-29
主要是瞭解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