非堆内存的参数配置

方法区配置
-XX:PerSize                    初始永久区的大小
-XX:MaxPermSize          最大永久区的大小

栈配置
-Xss             指定线程栈的大小

直接内存配置
直接内存跳过了Java堆,使java程序可以直接访问原生堆空间,它从一定程度上加快了内存空间的访问速度。

-XX:MaxDirectMemorySize        最大可用直接内存
-Xmx                                            若不设置,默认为最大堆空间大小

当直接内存使用量达到最大值时,就会触发垃圾回收,如果垃圾回收不能有效释放足够空间,直接内存溢出依然会引起系统的OOM

OutOfMemoryError
import java.nio.ByteBuffer;

/**
* Created by xxd on 2017/4/2.
*/
public class AccessDirectBuffer {
public void directAccess(){
long startTime = System.currentTimeMillis();
ByteBuffer bf = ByteBuffer.allocateDirect(500);
for (int i=0;i<100000;i++){
for (int j=0;j<99;j++){
bf.putInt(j);
}
bf.flip();
for (int j=0;j<99;j++){
bf.getInt();
}
bf.clear();
}
long endTime = System.currentTimeMillis();
System.out.println("testDirectWrite:"+(endTime - startTime));
}

public void bufferAccess(){
long startTime = System.currentTimeMillis();
ByteBuffer bf = ByteBuffer.allocate(500);
for (int i=0;i<100000;i++){
for (int j=0;j<99;j++){
bf.putInt(j);
}
bf.flip();
for (int j=0;j<99;j++){
bf.getInt();
}
bf.clear();
}
long endTime = System.currentTimeMillis();
System.out.println("testBufferWrite:"+(endTime - startTime));
}

public static void main(String[] args){
AccessDirectBuffer alloc = new AccessDirectBuffer();
alloc.bufferAccess();
alloc.directAccess();

alloc.bufferAccess();
alloc.directAccess();
}
}
执行结果:
第一次视为热身代码,则第二次直接内存的访问比堆内存访问快了大约70%(在我的计算机上)
虽然在访问读写上直接内存有较大的优势,但是在内存空间申请时,直接内存毫无优势可言:
import java.nio.ByteBuffer;

/**
* Created by xxd on 2017/4/2.
*/
public class AllocDirectBuffer {
public void directAllocate(){
long startTime = System.currentTimeMillis();
for (int i=0;i<200000;i++){
ByteBuffer bf = ByteBuffer.allocateDirect(1000);
}
long endTime = System.currentTimeMillis();
System.out.println("directAllocate : "+(endTime-startTime));
}
public void bufferAllocate(){
long startTime = System.currentTimeMillis();
for (int i=0;i<200000;i++){
ByteBuffer bf = ByteBuffer.allocate(1000);
}
long endTime = System.currentTimeMillis();
System.out.println("bufferAllocate : "+(endTime-startTime));
}

public static void main(String[] args){
AllocDirectBuffer adb = new AllocDirectBuffer();
adb.bufferAllocate();
adb.directAllocate();

adb.bufferAllocate();
adb.directAllocate();
}
}
执行结果:
只有第一次的时候直接内存的申请与堆内存的申请有较大差距,以后基本不相上下,此处与书上略有不同,看来已经被jvm优化了。

由此可以得出,直接内存适合申请次数少,访问较频繁的场合

如果内存空间本身需要频繁申请,则并不适合使用直接内存。

原文地址:https://www.cnblogs.com/xxdfly/p/4aaf80c81243f9225c725b52ad376d32.html