堆外内存也叫直接内存,指非JVM管理的内存,在操作系统内存里申请的。
import java.nio.ByteBuffer;
public class DirectMemory {
//堆内存读写测试-测试100000次,每次进行200次写操作,200次读操作,所耗时间
public static void headReadAndWrite(){
long startTime = System.currentTimeMillis();
//申请1kb堆内存
ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
for (int i =0 ;i< 100000; i++){
for (int j =0;j<200;j++){
byteBuffer.putInt(j);
}
//读写模式切换-切换到读模式
byteBuffer.flip();
for (int j =0;j<200;j++){
byteBuffer.getInt();
}
byteBuffer.clear();
}
long endTime = System.currentTimeMillis();
System.out.println("堆内存读写访问:"+ (endTime-startTime) +" ms");
}
//堆外内存读写-测试100000次,每次进行200次写操作,200次读操作,所耗时间
public static void directHeadReadAndWrite(){
long startTime = System.currentTimeMillis();
//申请1kb非堆内存
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1000);
for (int i =0 ;i< 100000; i++){
for (int j =0;j<200;j++){
byteBuffer.putInt(j);
}
//读写模式切换-切换到读模式
byteBuffer.flip();
for (int j =0;j<200;j++){
byteBuffer.getInt();
}
byteBuffer.clear();
}
long endTime = System.currentTimeMillis();
System.out.println("堆外内存读写访问:"+ (endTime-startTime) +" ms");
}
//堆内存申请-测试100000次,每次申请100b,所耗时间
public static void headAllocate(){
long startTime = System.currentTimeMillis();
for (int i =0 ;i< 100000; i++){
ByteBuffer.allocate(100);
}
long endTime = System.currentTimeMillis();
System.out.println("堆内存申请:"+ (endTime-startTime) +" ms");
}
//堆外内存申请内存-测试100000次,每次申请100b,所耗时间
public static void directHeadAllocate(){
long startTime = System.currentTimeMillis();
for (int i =0 ;i< 100000; i++){
ByteBuffer.allocateDirect(100);
}
long endTime = System.currentTimeMillis();
System.out.println("堆外内存申请:"+ (endTime-startTime) +" ms");
}
public static void main(String[] args) {
for (int i =0 ;i<10;i++){
headReadAndWrite();
directHeadReadAndWrite();
}
System.out.println();
for (int i =0 ;i<10;i++){
headAllocate();
directHeadAllocate();
}
}
}
上面代码执行结果可以看出:
- 堆外内存读写速度比堆内存要快很多
- 堆外内存的申请时间比堆内存要慢很多
上面bytebuffer堆内存对象存的是byte[]数组,而堆外内存对象存的是内存地址,因为堆外内存是申请操作系统内存,也就是C语言申请的内存,底层调用的本地方法(C语言的函数),内存地址引用指向该对象,读写操作都是C语言实现的。
DirectByteBuffer 内存回收
DirectByteBuffer(int cap) { // package-private
super(-1, 0, cap, cap);
boolean pa = VM.isDirectMemoryPageAligned();
int ps = Bits.pageSize();
long size = Math.max(1L, (long)cap + (pa ? ps : 0));
//1.申请内存前,会判断可用直接内存空间大小是否满足,不够的话会触发system.gc()回收掉JVM内directByteBuffer对象
Bits.reserveMemory(size, cap);
long base = 0;
try {
base = unsafe.allocateMemory(size);
} catch (OutOfMemoryError x) {
Bits.unreserveMemory(size, cap);
throw x;
}
unsafe.setMemory(base, size, (byte) 0);
if (pa && (base % ps != 0)) {
// Round up to page boundary
address = base + ps - (base & (ps - 1));
} else {
address = base;
}
//2.Cleaner注册机制,当JVM directByteBuffer回收后,会回调这里Deallocator线程回收堆外内存
cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
att = null;
}