第 10 章 一 直接内存 (向系统申请的内存)

第 10 章 直接内存

1、直接内存概述

直接内存

  1. 不是虚拟机运行时数据区的一部分,也不是《Java虚拟机规范》中定义的内存区域。
  2. 直接内存是在Java堆外的、直接向系统申请的内存区间。
  3. 来源于NIO,通过存在堆中的DirectByteBuffer操作Native内存
  4. 通常,访问直接内存的速度会优于Java堆。即读写性能高。
  5. 因此出于性能考虑读写频繁的场合可能会考虑使用直接内存。
  6. Java的NIO库允许Java程序使用直接内存,用于数据缓冲区

代码示例

  • 代码
/**
 *  IO                  NIO (New IO / Non-Blocking IO)
 *  byte[] / char[]     Buffer
 *  Stream              Channel
 *
 * 查看直接内存的占用与释放
 */
public class BufferTest {
    private static final int BUFFER = 1024 * 1024 * 1024;//1GB

    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();
    }
}
  • 直接占用了 1G 的本地内存

image-20200729214811954

  • 释放后,Java程序的内存占用明显减少

image-20200729214909938

2、BIO 与 NIO

非直接缓存区(BIO)

  • 原来采用BIO的架构,在读写本地文件时,我们需要从用户态切换成内核态

image-20200709170907611

直接缓冲区(NIO)

  • NIO 直接操作物理磁盘,省去了中间商赚差价

image-20200729215128430

代码测试

  • 测试代码:分别使用 BIO 和 NIO 复制大文件,看看用时差别
/**
 * @author shkstart  shkstart@126.com
 * @create 2020  0:04
 */
public class BufferTest1 {

    private static final String TO = "F:\\test\\异界BD中字.mp4";
    private static final int _100Mb = 1024 * 1024 * 100;

    public static void main(String[] args) {
        long sum = 0;
        String src = "F:\\test\\异界BD中字.mp4";
        for (int i = 0; i < 3; i++) {
            String dest = "F:\\test\\异界BD中字_" + i + ".mp4";
            // sum += io(src,dest);//54606
            sum += directBuffer(src, dest);//50244
        }

        System.out.println("总花费的时间为:" + sum);
    }

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

            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }


        long end = System.currentTimeMillis();

        return end - start;
    }
}

深入 ByteBuffer 源码

  • ByteBuffer.allocateDirect() 方法
public static ByteBuffer allocateDirect(int capacity) {
    return new DirectByteBuffer(capacity);
}
  • DirectByteBuffer 类的构造器用到了 Unsafe 类分配本地内存
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));
    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;
    }
    cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
    att = null;
}

3、直接内存与 OOM

  1. 直接内存也可能导致OutofMemoryError异常
  2. 由于直接内存在Java堆外,因此它的大小不会直接受限于-Xmx指定的最大堆大小,但是系统内存是有限的Java堆和直接内存的总和依然受限于操作系统能给出的最大内存。
  3. 直接内存的缺点为:
    • 分配回收成本较高
    • 不受JVM内存回收管理
  4. 直接内存大小可以通过MaxDirectMemorySize设置
  5. 如果不指定,默认与堆的最大值-Xmx参数值一致

代码示例 1

  • 代码
/**
 * 本地内存的OOM:  OutOfMemoryError: Direct buffer memory
 *
 * @author shkstart  shkstart@126.com
 * @create 2020  0:09
 */
public class BufferTest2 {
    private static final int BUFFER = 1024 * 1024 * 20;//20MB

    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);
        }
    }
}
  • 本地内存持续增长,直至程序抛出异常:java.lang.OutOfMemoryError: Direct buffer memory

image-20200729215912722

  • 异常信息
Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory
	at java.nio.Bits.reserveMemory(Bits.java:694)
	at java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:123)
	at java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:311)
	at com.atguigu.java.BufferTest2.main(BufferTest2.java:21)

Process finished with exit code 1

代码示例 2

  • 代码:直接通过 Unsafe 类申请本地内存
/**
 * -Xmx20m -XX:MaxDirectMemorySize=10m
 * @author shkstart  shkstart@126.com
 * @create 2020  0:36
 */
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);
        }
    }
}`
  • JVM 参数
-Xmx20m -XX:MaxDirectMemorySize=10m
  • 抛出 OOM 异常
Exception in thread "main" java.lang.OutOfMemoryError
	at sun.misc.Unsafe.allocateMemory(Native Method)
	at com.atguigu.java.MaxDirectMemorySizeTest.main(MaxDirectMemorySizeTest.java:20)

Process finished with exit code 1

JDK8 中元空间直接使用本地内存

image-20200729221624142

1.何为内存模块 (Memory Module)? 内存模块是指一个印刷电路板表面上有镶嵌数个记忆体芯片chips,而这内存芯片通常是DRAM芯片,但近来系统设计也有使用快取隐藏式芯片镶嵌在内存模块上内存模块是安装在PC 的主机板上的专用插槽(Slot)上镶嵌在Module上DRAM芯片(chips)的数量和个别芯片(chips)的容量,是决定内存模块的设计的主要因素。 2.什么是Parity? 早先所使用的存储器数据检错方式是Parity Check,其是以每8比特增加1比特的方式进行检错。因此若是具备Parity的存储器,其数据宽度将比非parity的存储器为大。不过若以 Parity的检错方式看,其多出的奇偶位事实上只用于分辨奇数或偶数个比特数。这种方式仅能得知是某一位发生错误,并无法确定是哪一个位置发生错误,而且无法运用在双数位的检错上。 3.什么是ECC? ECC是另一种更为进步的存储器数据检错机制。其工作的方式与Parity不同,并不是采用单一比特的方式来进行检错,而是采用数据块(block)概念与复杂的演算方法来修正数据。因此不仅能检测多位比特错误,还能进行修正单一比特的错误。 4.SPD的作用是什么? 为Serial Presence Detect 的缩写,它是烧录在EEPROM内的码,以往开机时BIOS必须侦测memory,但有了SPD就不必再去作侦测的动作,而由BIOS直接读取 SPD取得内存的相关资料。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

white camel

感谢支持~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值