直接内存概述

  • 不是虚拟机运行时数据区的一部分,也不是《Java虚拟机规范》中定义的内存区域。
  • 直接内存是在Java堆外的、直接向系统申请的内存区间。
  • 来源于NIO,通过存在堆中的DirectByteBuffer操作Native内存
  • 通常,访问直接内存速度会由于Java堆,即读写性能高。

    • 因为出于性能考虑,读写频繁的场合可能会考虑使用直接内存。
    • Java的NIO库允许Java程序使用直接内存,用于数据缓冲区

直接内存占用代码示例

  1. /**
  2. * 查看直接内存的占用与释放
  3. */
  4. public class BufferTest {
  5. private static final int BUFFER = 1024 * 1024 * 1024; // 1GB
  6. public static void main(String[] args) {
  7. // 直接分配本地内存空间
  8. ByteBuffer byteBuffer = ByteBuffer.allocateDirect(BUFFER);
  9. System.out.println("直接内存分配完毕,请求指示!");
  10. Scanner scanner = new Scanner(System.in);
  11. scanner.next();
  12. System.out.println("直接内存开始释放!");
  13. byteBuffer = null;
  14. System.gc();
  15. scanner.next();
  16. }
  17. }

运行后,根据jps指令查看PID,在任务管理器中可以看到具体的内存占用

  1. > jps
  2. 20192 BufferTest

11-直接内存 - 图1

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

11-直接内存 - 图2

可以看到内存占用降到18.3M

使用直接内存的原因

  1. 读写文件,需要与磁盘交互,需要由用户态切换到内核太。在内核太时,需要内存如下图的操作,使用IO,这里需要两份内存存储重复数据,效率低

11-直接内存 - 图3

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

11-直接内存 - 图4

代码示例:

  1. /**
  2. * io与nio例子
  3. */
  4. public class BufferTest1 {
  5. private static final String FILE = "D:\\迅雷下载\\新建文件夹\\XXX.mkv";
  6. private static final int _10Mb = 1024 * 1024 * 10;
  7. public static void main(String[] args) {
  8. long sum = 0;
  9. String src = FILE;
  10. for (int i = 0; i < 3; i++) {
  11. String dest = "D:\\迅雷下载\\新建文件夹\\XXX" + i + ".mkv";
  12. sum += directBudder(src, dest); // 总花费时间为:31345
  13. // sum += io(src, dest); // 总花费时间为:62520
  14. }
  15. System.out.println("总花费时间为:" + sum);
  16. }
  17. private static long directBudder(String src, String dest) {
  18. long start = System.currentTimeMillis();
  19. FileChannel inChannel = null;
  20. FileChannel outChannel = null;
  21. try {
  22. inChannel = new FileInputStream(src).getChannel();
  23. outChannel = new FileOutputStream(dest).getChannel();
  24. ByteBuffer byteBuffer = ByteBuffer.allocateDirect(_10Mb);
  25. while (inChannel.read(byteBuffer) != -1) {
  26. byteBuffer.flip(); // 修改为读数据模式
  27. outChannel.write(byteBuffer);
  28. byteBuffer.clear(); // 清空
  29. }
  30. } catch (IOException e) {
  31. e.printStackTrace();
  32. } finally {
  33. if (inChannel != null) {
  34. try {
  35. inChannel.close();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. if (outChannel != null) {
  41. try {
  42. outChannel.close();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. }
  48. long end = System.currentTimeMillis();
  49. return end - start;
  50. }
  51. private static long io(String src, String dest) {
  52. long start = System.currentTimeMillis();
  53. FileInputStream fis = null;
  54. FileOutputStream fos = null;
  55. try {
  56. fis = new FileInputStream(src);
  57. fos = new FileOutputStream(dest);
  58. byte[] buffer = new byte[_10Mb];
  59. while (true) {
  60. int len = fis.read(buffer);
  61. if (len == -1) {
  62. break;
  63. }
  64. fos.write(buffer, 0, len);
  65. }
  66. } catch (IOException e) {
  67. e.printStackTrace();
  68. }
  69. long end = System.currentTimeMillis();
  70. return end - start;
  71. }
  72. }

结论:在视频大小1.5G的情况下,io耗时62520,nio耗时31345,nio较快

直接内存的特性:

  • 也可能导致OutOfMemoryError异常
  • 由于直接内存在Java堆外,因此它的大小不会直接受限于-Xmx指定的最大堆大小,但是系统内存是有限的,Java堆和直接内存和依然受限于操作系统能给出的最大内存。
  • 缺点:

    • 分配回收成本较高
    • 不受JVM内存回收管理
  • 直接内存大小可以通过-XX:MaxDirectMemorySize设置
  • 如果不指定,默认与堆的最大值-Xmx参数值一致。

直接内存 OOM代码示例

  1. /**
  2. * 本地内存OOM OutOfMemoryError: Direct buffer memory
  3. */
  4. public class BufferTest2 {
  5. private static final int BUFFER = 1024 * 1024 * 20; // 20MB
  6. public static void main(String[] args) {
  7. ArrayList<ByteBuffer> list = new ArrayList<>();
  8. int count = 0;
  9. try {
  10. while (true) {
  11. // 使用直接内存
  12. ByteBuffer byteBuffer = ByteBuffer.allocateDirect(BUFFER);
  13. list.add(byteBuffer);
  14. count++;
  15. try {
  16. Thread.sleep(100);
  17. } catch (InterruptedException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. }finally {
  22. System.out.println(count);
  23. }
  24. }
  25. }

运行结果:

  1. 362
  2. Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory
  3. at java.nio.Bits.reserveMemory(Bits.java:694)
  4. at java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:123)
  5. at java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:311)
  6. at BufferTest2.main(BufferTest2.java:19)

UnSafe OutOfMemoryError代码示例

  1. /**
  2. * -Xmx20m -XX:MaxDirectMemorySize=10m
  3. */
  4. public class MaxDirectMemorySizeTest {
  5. private static final long _1MB = 1024 * 1024;
  6. public static void main(String[] args) throws IllegalAccessException {
  7. Field unsafeField = Unsafe.class.getDeclaredFields()[0];
  8. unsafeField.setAccessible(true);
  9. Unsafe unsafe = (Unsafe) unsafeField.get(null);
  10. while (true) {
  11. unsafe.allocateMemory(_1MB);
  12. }
  13. }
  14. }

运行结果:

  1. Exception in thread "main" java.lang.OutOfMemoryError
  2. at sun.misc.Unsafe.allocateMemory(Native Method)
  3. at MaxDirectMemorySizeTest.main(MaxDirectMemorySizeTest.java:17)

结论:直接内存也会OOM

11-直接内存 - 图5

简单理解:

  1. java process memory = java heap + native memory