What is Memory mapping in java?

การทำแผนที่หน่วยความจำใน java เป็นแนวคิดที่ระดับต่ำจะทำให้ไฟล์ I / O ได้อย่างมีประสิทธิภาพมากขึ้น. Generally we use stream or buffer stream to do file I/O. Although buffered stream is widely used to increase the performance of file input and output, but memory mapping is the ultimate technique that can be used to increase the performance drastically. In memory map, the physical file is mapped with the memory and then the I/O is performed in the mapped memory directly. As a result the I/O is performed on the physical file itself. But you need to be careful about the memory usage. It is always recommended to map the memory in small chunks and then read/write on the file. It increases the performance and also releases the memory after use. If you want to map the entire big file into memory then it might hang the system itself.

ในตัวอย่างต่อไปนี้, เราจะใช้ RandomAccessFile การอ่านและเขียน. เราจะสร้างช่องไฟล์แล้วใช้หน่วยความจำเพื่อทำแผนที่ map ไฟล์ที่มีหน่วยความจำ. นี่ MappedByteBuffer เป็นบัฟเฟอร์โดยตรงที่จะใช้กับไฟล์. ในขณะที่การทำแผนที่คุณต้องพูดถึงจุดเริ่มต้นและสิ้นสุดหรืออ่านหรือเขียน. เทคนิคนี้ช่วยให้คุณสามารถแมภูมิภาคโดยเฉพาะอย่างยิ่งของไฟล์และดำเนินการแฟ้ม I / O.

โค้ดตัวอย่าง:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package JavaTips.com;

นำเข้า java.io. *;
นำเข้า java.nio. *;
java.nio.channels นำเข้า. *;

/**
*
* @ ผู้ kaushikp
*/
JavaMemoryMap เรียนสาธารณะ {

/**
* @ พระราม args อาร์กิวเมนต์บรรทัดคำสั่ง
*/

int ยาวคงที่ = 2048; // 128 Mb
ประชาชนเป็นโมฆะหลักแบบคงที่(เชือก[] args) ยกเว้นพ่น {

//สร้าง RandomAccessFile และ FileChannel
RandomAccessFile อากาศ = RandomAccessFile ใหม่(“memorymaptest.dat”, “RW”);
FileChannel FC = raf.getChannel();

//การทำแผนที่ไฟล์โดยใช้ช่องทางไฟล์
MappedByteBuffer mbb1 = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
MappedByteBuffer mbb2 = fc.map(FileChannel.MapMode.READ_WRITE, 1024, 2048);

//การเขียนเนื้อหาในไฟล์แมป
สำหรับ(int i = 0; ผม < 1024; i )
mbb1.put((ไบต์)'X');
System.out.println(“เสร็จ XXX เขียน”);

สำหรับ(int i = 0; ผม < 1024; i )
mbb2.put((ไบต์)'และ');
System.out.println(“เสร็จ yyy เขียน”);
}
}

============================================= ============================================== ซื้อหนังสือ techalpine ที่ดีที่สุดใน Amazon,en,ช่างไฟฟ้า CT Chestnutelectric,en
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share