直接内存概述
- 不是虚拟机运行时数据区的一部分,也不是《Java虚拟机规范》中定义的内存区域。
- 直接内存是在Java堆外的、直接向系统申请的内存区间。
- 来源于NIO,通过存在堆中的DirectByteBuffer操作Native内存
通常,访问直接内存速度会由于Java堆,即读写性能高。
- 因为出于性能考虑,读写频繁的场合可能会考虑使用直接内存。
- Java的NIO库允许Java程序使用直接内存,用于数据缓冲区
直接内存占用代码示例
/*** 查看直接内存的占用与释放*/public class BufferTest {private static final int BUFFER = 1024 * 1024 * 1024; // 1GBpublic static void main(String[] args) {// 直接分配本地内存空间ByteBuffer byteBuffer = ByteBuffer.allocateDirect(BUFFER);System.out.println("直接内存分配完毕,请求指示!");Scanner scanner = new Scanner(System.in);scanner.next();System.out.println("直接内存开始释放!");byteBuffer = null;System.gc();scanner.next();}}
运行后,根据jps指令查看PID,在任务管理器中可以看到具体的内存占用
> jps20192 BufferTest

可以看到占用1G多的内存空间,随便输入一串文字

可以看到内存占用降到18.3M
使用直接内存的原因
读写文件,需要与磁盘交互,需要由用户态切换到内核太。在内核太时,需要内存如下图的操作,使用IO,这里需要两份内存存储重复数据,效率低

使用NIO时,如下图,操作系统划分出的直接缓存区可以被Java代码直接访问,只有一份。NIO适合对大文件的读写操作。

代码示例:
/*** io与nio例子*/public class BufferTest1 {private static final String FILE = "D:\\迅雷下载\\新建文件夹\\XXX.mkv";private static final int _10Mb = 1024 * 1024 * 10;public static void main(String[] args) {long sum = 0;String src = FILE;for (int i = 0; i < 3; i++) {String dest = "D:\\迅雷下载\\新建文件夹\\XXX" + i + ".mkv";sum += directBudder(src, dest); // 总花费时间为:31345// sum += io(src, dest); // 总花费时间为:62520}System.out.println("总花费时间为:" + sum);}private static long directBudder(String src, String dest) {long start = System.currentTimeMillis();FileChannel inChannel = null;FileChannel outChannel = null;try {inChannel = new FileInputStream(src).getChannel();outChannel = new FileOutputStream(dest).getChannel();ByteBuffer byteBuffer = ByteBuffer.allocateDirect(_10Mb);while (inChannel.read(byteBuffer) != -1) {byteBuffer.flip(); // 修改为读数据模式outChannel.write(byteBuffer);byteBuffer.clear(); // 清空}} catch (IOException e) {e.printStackTrace();} finally {if (inChannel != null) {try {inChannel.close();} catch (IOException e) {e.printStackTrace();}}if (outChannel != null) {try {outChannel.close();} catch (IOException e) {e.printStackTrace();}}}long end = System.currentTimeMillis();return end - start;}private static long io(String src, String dest) {long start = System.currentTimeMillis();FileInputStream fis = null;FileOutputStream fos = null;try {fis = new FileInputStream(src);fos = new FileOutputStream(dest);byte[] buffer = new byte[_10Mb];while (true) {int len = fis.read(buffer);if (len == -1) {break;}fos.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();}long end = System.currentTimeMillis();return end - start;}}
结论:在视频大小1.5G的情况下,io耗时62520,nio耗时31345,nio较快
直接内存的特性:
- 也可能导致OutOfMemoryError异常
- 由于直接内存在Java堆外,因此它的大小不会直接受限于-Xmx指定的最大堆大小,但是系统内存是有限的,Java堆和直接内存和依然受限于操作系统能给出的最大内存。
缺点:
- 分配回收成本较高
- 不受JVM内存回收管理
- 直接内存大小可以通过-XX:MaxDirectMemorySize设置
- 如果不指定,默认与堆的最大值-Xmx参数值一致。
直接内存 OOM代码示例
/*** 本地内存OOM OutOfMemoryError: Direct buffer memory*/public class BufferTest2 {private static final int BUFFER = 1024 * 1024 * 20; // 20MBpublic static void main(String[] args) {ArrayList<ByteBuffer> list = new ArrayList<>();int count = 0;try {while (true) {// 使用直接内存ByteBuffer byteBuffer = ByteBuffer.allocateDirect(BUFFER);list.add(byteBuffer);count++;try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}finally {System.out.println(count);}}}
运行结果:
362Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memoryat java.nio.Bits.reserveMemory(Bits.java:694)at java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:123)at java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:311)at BufferTest2.main(BufferTest2.java:19)
UnSafe OutOfMemoryError代码示例
/*** -Xmx20m -XX:MaxDirectMemorySize=10m*/public class MaxDirectMemorySizeTest {private static final long _1MB = 1024 * 1024;public static void main(String[] args) throws IllegalAccessException {Field unsafeField = Unsafe.class.getDeclaredFields()[0];unsafeField.setAccessible(true);Unsafe unsafe = (Unsafe) unsafeField.get(null);while (true) {unsafe.allocateMemory(_1MB);}}}
运行结果:
Exception in thread "main" java.lang.OutOfMemoryErrorat sun.misc.Unsafe.allocateMemory(Native Method)at MaxDirectMemorySizeTest.main(MaxDirectMemorySizeTest.java:17)
结论:直接内存也会OOM

简单理解:
java process memory = java heap + native memory
