第十一章 直接内存

11.1 概述

直接内存(Direct Memory),不是虚拟机运行时数据区的一部分,也不是《Java 虚拟机规范》中定义的内存区域

直接内存是在 Java 堆外的、直接向系统申请的内存区间

来源于 NIO,通过存在堆中的 DirectByteBuffer 操作 Native 内存

通常,访问直接内存的速度会优于 Java 堆。即读写性能高

  • 因此处于性能考虑,读写频繁的场合可能会考虑使用直接内存

  • Java 的 NIO 库允许 Java 程序使用直接内存,用于数据缓冲区

代码演示

/**
 * IO                   NIO(New IO / Non-Blocking IO)
 * byte[] / char[]      Buffer
 * Stream               Channel
 *
 * 查看直接内存的占用与释放
 */
public class BufferTest {

    //1GB
    private static final int BUFFER = 1024 * 1024 * 1024;

    public 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();
    }

}

运行后

直接内存分配完毕,请求指示!

在 cmd 窗口下运行jps,之后找到BufferTest对应的进程 id

image

再打开任务管理器,找到对应进程 id 的应用

image

1093988 / 1024 / 1024 ≈ 1.04 GB

然后在代码中释放内存,即输入释放内存即可

直接内存分配完毕,请求指示!
释放内存
直接内存开始释放!

image

可以发现占用的内存少了很多

54136 / 1024 / 1024 ≈ 0.05 GB

最后关闭进程,即输入关闭即可

直接内存分配完毕,请求指示!
释放内存
直接内存开始释放!
关闭

11.1.1 非直接缓存区

读写文件,需要与磁盘交互,需要由用户态切换到内核态。在内核态时,需要内存如图的操作

使用 IO,如图。这里需要两份内存存储重复数据,效率低

image

11.1.2 直接缓存区

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

image

11.1.3 代码演示

使用传统的 IO 和 NIO 的对比

public class BufferTest1 {

    private static final String To = "F:\\tet\\xxx.mp4";
    private static final int _100Mb = 100 * 1024 * 1024;

    public static void main(String[] args) {
        long sum = 0;
        //1.5 GB的电影
        String src = "F:\\tet\\xxx.mp4";
        for (int i = 0; i < 3; i++) {
            String dest = "F:\\tet\\xxx_" + i + ".mp4";
//            sum += io(src, dest);//54606
            sum += directBuffer(src, dest);//50244
        }

    }

    private static long directBuffer(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(_100Mb);
            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[_100Mb];
            while (true) {
                int len = fis.read(buffer);
                if (len == -1) {
                    break;
                }
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        long end = System.currentTimeMillis();
        return end - start;
    }

}

直接缓存比较快

11.2 OOM 异常

也可能导致 OutOfMemoryError 异常

由于直接内存在 Java 堆外,因此它的大小不会直接受限于-Xmx指定的最大堆大小,但是系统内存是有限的,Java 堆和直接内存的总和依然受限于操作系统能给出的最大内存

代码演示

/**
 * 本地内存的 OOM:OutOfMemoryError: Direct buffer memory
 */
public class BufferTest2 {

    private static final int BUFFER = 1024 * 1024 * 20;//20 MB

    public 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:" + count);
        }

    }

}

结果如下:

count:173
Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory
	at java.nio.Bits.reserveMemory(Bits.java:693)
	at java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:123)
	at java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:311)
	at jvm.chapter11.BufferTest2.main(BufferTest2.java:19)

11.3 缺点及设置值

缺点:

  • 分配回收成本较高

  • 不受 JVM 内存回收管理

直接内存大小可以通过MaxDirectMemorySize设置

如果不指定,默认与堆的最大值-Xmx参数一致

《深入理解 Java 虚拟机》中的例子

/**
 * -Xmx20m -XX:MaxDirectMemorySize=10m
 */
public class MaxDirectMemorySizeTest {

    private static final long _1MB = 1024 * 1024;

    public static void main(String[] args) throws IllegalAccessException {
        Field unsafeFiled = Unsafe.class.getDeclaredFields()[0];
        unsafeFiled.setAccessible(true);
        Unsafe unsafe = (Unsafe)unsafeFiled.get(null);
        while (true) {
            unsafe.allocateMemory(_1MB);
        }
    }

}

结果如下:

Exception in thread "main" java.lang.OutOfMemoryError
	at sun.misc.Unsafe.allocateMemory(Native Method)
	at jvm.chapter11.MaxDirectMemorySizeTest.main(MaxDirectMemorySizeTest.java:19)

11.4 小结

image

posted @ 2026-06-01 10:31  清风含薰  阅读(1)  评论(0)    收藏  举报