0
点赞
收藏
分享

微信扫一扫

十、JVM-直接内存(基础篇)

以沫的窝 2023-05-06 阅读 111

一、概述

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

NIO操作本地内存演示

package com.lori.devops.controller.java9;

import java.nio.ByteBuffer;
import java.util.Scanner;

/**
 * 查看直接内存的占用与释放
 */
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();
    }
}
  • 查询进程号,查询占用内存大小:1041/1024=1.01GB 192.png

二、直接内存和jvm内存的区别

原来采用BIO的架构,在读写本地文件时,我们使用的是jvm分配的内存,需要从用户态切换成内核态 193.png 而NIO中的 DirectByteBuffer 直接操作 本地内存 操作磁盘,省去用户态和内核态之间的切换消耗 194.png 例子

package com.atguigu.java;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
 
/**
 * @author 
 * @create 
 */
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 耗时ms
            sum += directBuffer(src,dest);//50244 耗时ms
        }
 
        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;
    }
}

三、直接内存存在的问题

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

在上面的 DirectByteBuffer 中,其底层也是通过 Unsafe 类来开辟 直接内存的,下面用反射的方式 直接进行分配

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.OutOfMemoryError
	at sun.misc.Unsafe.allocateMemory(Native Method)
	at com.atguigu.java.MaxDirectMemorySizeTest.main(MaxDirectMemorySizeTest.java:20)

195.png

举报

相关推荐

0 条评论