Android 内存管理:java/native heap内存、虚拟内存、处理器内存

514 阅读6分钟

一, 如何避免new byte[cap] 的时候OOM?

上代码:

public boolean isMemoryEnough(int requiredMemory) {
        Log.d(TAG, "allocate memory:" + requiredMemory);
        Runtime runtime = Runtime.getRuntime();
        //Maximum jvm memory size in the process
        long max_memory = runtime.maxMemory();
        //The JVM memory size requested in the process does not necessarily allocate that much memory (will change over time)
        long apply_memory = runtime.totalMemory();
        //The jvm memory size that can be used in the process application memory
        long free_memory = runtime.freeMemory();
        //JVM memory used in the process
        long use_memory = apply_memory - free_memory;
        //Calculate the memory usage of jvm. If it exceeds 0.8, you need to be vigilant.
        float use_memory_rate = ((float) use_memory) / max_memory;
        long actual_free_memory = max_memory - use_memory;
        Log.d(TAG, "max_memory=: " + max_memory + ", use_memory=: " + use_memory + ",actual_free_memory=" + actual_free_memory + ", use_memory_rate=: " + use_memory_rate);
        return actual_free_memory >= requiredMemory;
    }

转载自:

1.jvm 堆内存(dalvik 堆内存)

不同手机中app进程的 jvm 堆内存是不同的,因厂商在出厂设备时会自定义设置其峰值。比如,在Android Studio 创建模拟器时,会设置jvm heap 默认384m
当app 进程中java 层 new 对象(加起来总和)占用的堆内存达到jvm heap 峰值时,就会抛出OOM 。

通过一个案例进一步,了解jvm 堆内存

通过以下代码,可获取到进程中jvm 堆内存的使用情况:

    public JSONObject statisticsJVMMemory() {
        JSONObject json = new JSONObject();
        Runtime runtime = Runtime.getRuntime();
        //进程中最大jvm 内存大小
        long max_memory = runtime.maxMemory() / 1024;
        //进程中申请的jvm内存大小,不等用于一定分配那么多内存(会随着时间变化而变化)
        long apply_memory = runtime.totalMemory() / 1024;
        //进程中申请内存中可使用的jvm内存大小
        long free_memory = runtime.freeMemory() / 1024;
        //进程中已经使用的jvm 内存
        long use_memory = apply_memory - free_memory;
        //计算出jvm 的内存使用率,超过0.8就需要警惕,可能java 层内存存在泄漏
        float use_memory_rate = ((float) use_memory) / max_memory;
        //....
     }

先来了解jvm 堆内存的几个指标:
1.最大限制内存: maxMemory,出厂时设置的
2.申请的内存: totalMemory,不等用于一定分配那么多内存(会随着时间变化而变化)
3.(申请的内存中)剩余使用的内存:freeMemory
4.已使用的内存: use_memory=totalMemory -freeMemory, 重点关注是这个
5.内存使用率: use_memory/maxMemory

模拟jvm 堆内存一直上涨的场景, 启动一个线程,周期性间隔几秒,不断模拟创建byte 数组, 然后统计app 进程的jvm 堆内存使用情况 :

        private List<byte[]> jvmLeakList = new ArrayList<>();
        public void addJvmLeak() {
            byte[] largeByte = new byte[50 * 1024 * 1024];
            for (int i = 0; i < largeByte.length; ++i) {
                largeByte[i] = 'a';//分配使用时,进程内存中物理内存才会使用
            }
            Log.i(TAG, "byte size: " + (largeByte.length / 1024 / 1024) + " mB");
            jvmLeakList.add(largeByte);
        }

查看输出日志 , 对比前后两次的堆内存变化:

多执行几次后,会触发oom 。先来看下oom 前的内存状况:

系统会主动触发gc ,输出art: Starting a blocking GC Allocart: Alloc sticky concurrent mark sweep GC freed 0(0B) AllocSpace objects日志 ,解读如下:

当内存不足32m时,再次new 一个50M的byte 数组,就会抛出oom:

app 进程中真正剩余可用 jvm 堆内存是

       //真正可用的内存,包含剩余可申请的内存
       long actual_free_memory=max_memory-use_memory;
12

处理jvm 内存不足的情况

当大型app或者游戏app 遇到 jvm 内存(大多数为384m)不足时,可通过android:largeHeap="true"来增加,jvm 堆内存 会调整为512M峰值。

2.native内存

获取app 进程的native 堆内存,代码如下:

    /**
     * adb shell dumpsys meminfo packageName包名:
     * 查看每个进程中内存状况(包含jvm 和native 、shareLib)
     *
     * @return
     */
    private JSONObject statisticsNativeMemory() {
        JSONObject jsonObject = new JSONObject();
         // 当前进程中native层申请的堆内存,会随着时间而变化,加大或者减少
        long totalNative = Debug.getNativeHeapSize() / 1024 / 1024;
        //当进程中native层中已使用堆内存
        long useNative = Debug.getNativeHeapAllocatedSize() / 1024 / 1024;
        //当前进程中native层中剩余的堆内存
        long freeNative = Debug.getNativeHeapFreeSize() / 1024 / 1024;
        //....
 }

在android 8.0 以后,bitamp 所占内存从jvm 堆内存移到native内存中,大大减少了oom的风险:

通过一个案例来进一步了解:

在android 8.0以上非64位的设备验证:

      public void addNativeLeak() {
            /**
             * 在android 8.0 以上版本, bitmap内存放到native层内存中,非jvm 堆内存中
             *
             * Bitmap.Config.ARGB_8888:一个像素占用4 byte
             * Bitmap的内存大小=像素*4byte
             */
            int width = 1024 * 8;
            int height = 1024 * 8;
            //bitmap 被创建时,会申请虚拟内存 256m=1024*8*1024*8*4
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            boolean draw=false;
            if (draw) {
                //当给bitmap绘制内容时,物理内存会增加; 物理内存是当真正需要使用时才会用到
                Canvas canvas = new Canvas(bitmap);
                paint.setAntiAlias(true);
                paint.setColor(Color.WHITE);
                canvas.drawCircle(width / 2, height / 2, width / 2, paint);
            }
            int pictureSize = bitmap.getByteCount() / 1024 / 1024;
            int bitmapSize = bitmap.getAllocationByteCount() / 1024 / 1024;
            Log.i(TAG, "bitmap size: " + bitmapSize + " mB" + " ,picture size: " + pictureSize + " mB");
            nativeLeakList.add(bitmap);
        }

启动一个线程,间隔几秒, 创建一个256m的bitmap ,输出当前native 内存情况:

当native 堆内存不断上涨,虚拟内存也会增加,直到oom。系统会输出Starting a blocking GC NativeAlloc标识当前native层内存不足。来看下, oom 前的native 内存情况:

3.app 进程中虚拟内存

先来了解下进程中虚拟内存与物理内存 概念

PSS(Proportional Set Size): 物理内存,PSS = USS + 按比例包含共享库

RSS(Resident Set Size): 物理内存,RSS = USS + 包含共享库

VSS(Virtual Set Size): 虚拟内存,VSS = RSS + 未分配实际物理内存

虚拟内存: 虚拟内存是计算机系统内存管理的一种技术。它使得应用程序认为它拥有连续的可用的内存(一个连续完整的地址空间),而实际上,它通常是被分隔成多个物理内存碎片,还有部分暂时存储在外部磁盘存储器上,在需要时进行数据交换(来源百度百科)。在32位的app进程中,虚拟内存最大4G,往往3G就oom了。

更多虚拟内存知识,请阅读虚拟内存-维基百科。

获取app进程中虚拟内存和物理内存的方式:

    /**
     * 计算进程中内存状况和线程状况:
     * FDSize: 128  // 当前分配的文件描述符,这个值不是当前进程使用文件描述符的上线
     * VmPeak:  4403108 kB    // 当前进程运行过程中所占用内存的峰值
     * VmSize:  4402056 kB    // 已用逻辑空间地址,虚拟内存大小。整个进程使用虚拟内存大小,是VmLib, VmExe, VmData, 和 VmStk的总和。
     * VmLck:         0 kB
     * VmPin:         0 kB
     * VmHWM:     49108 kB    // 程序得到分配到物理内存的峰值
     * VmRSS:     48920 kB    // 程序现在正在使用的物理内存
     * RssAnon:            9268 kB
     * RssFile:           39540 kB
     * RssShmem:            112 kB
     * VmData:  1737808 kB        // 所占用的虚拟内存
     * VmStk:      8192 kB        // 任务在用户态的栈的大小 (stack_vm)
     * VmExe:        20 kB        // 程序所拥有的可执行虚拟内存的大小,代码段,不包括任务使用的库 (end_code-start_code)
     * VmLib:    163804 kB        // 被映像到任务的虚拟内存空间的库的大小 (exec_lib)
     * VmPTE:      1000 kB        // 该进程的所有页表的大小,单位:kb
     * Threads:        17        // 当前的线程数
     *
     * @return
     */
    public JSONObject statisticsProcessMemory() {

        JSONObject json = new JSONObject();
        // Linux 的/proc/self/status文件。这个并不是一个真实存在的文件,而为 Linux 的一个内核接口
        File file = new File(ProcCmd.cmd_app_status);
        readFileLine(file, (line) -> {
            try {
                String s = null;
                if (line.startsWith(MemoryKeys.ProcessKeys.key_threads)) {
                    //进程中线程的数量
                    s = line;
                } else if (line.startsWith(MemoryKeys.ProcessKeys.key_vm_size)) {
                    //整个进程中虚拟内存的总和(= VmLib+VmExe+VmData+VmStk),会动态变化增加
                    s = line;
                } else if (line.startsWith(MemoryKeys.ProcessKeys.key_vm_rss)) {
                    // 进程中当前物理内存,即系统实际在物理内存上分配给程序的内存
                    s = line;
                }
            //.....
        });
    }

还是以上面的bitmap 为例子,间隔几秒创建bitmap 时,看虚拟内存和物理内存的变化:
在这里插入图片描述
32位进程虚拟内存3G多的问题

等待多执行几次后,虚拟内存就耗尽,会oom:

在32位设备上app 进程中虚拟内存是3G 多,在一些沙盒插件化32位运行环境下,游戏项目很容易虚拟内存耗尽。

32位进程和64进程的内存分配情况如下所示

每个进程中虚拟内存都是隔离的,互不干扰。

4.手机系统内存(处理器内存)

每个手机的处理器内存都是出厂时设置的,处理器内存也是物理内存。

解读下

  • MemTotal: 处理器内存,即多少G 运行内存
  • MemAvailable: 算法算出可用物理内存,包含可回收使用的内存 ,若是该值很少,则会触发oom.

获取手机内存的代码如下:

  /**
     * 统计系统内存
     * MemTotal: 处理器内存,即多少G 运行内存
     * MemAvailable: 算法算出可用内存,包含可回收使用的内存 ,通常看这个
     * @return
     */
    public JSONObject statisticsSystemMemory() {
        JSONObject json = new JSONObject();
        //"/proc/meminfo"
        File file = new File(ProcCmd.cmd_system_meminfo);
        readFileLine(file, new Block() {
            long total, available;
            @Override
            public void block(String line) {
                try {
                    String s = null;
                    if (line.startsWith(MemoryKeys.SystemKeys.key_mem_total)) {
                        //手机处理器的内存,运行多少G
                        s = line;
                    } else if (line.startsWith(MemoryKeys.SystemKeys.key_mem_free)) {
                        //手机系统剩余内存,不包含可回收的内存。[MemTotal-MemFree]就是已被用掉的内存
                        s = line;
                    } else if (line.startsWith(MemoryKeys.SystemKeys.key_mem_available)) {
                        //手机系统可用内存:动态计算出的可用内存,包含mem_free + 可回收使用的内存,该值是一个估值。
                        s = line;
                    }
                //....
        });
        return json;
    }
123456789101112131415161718192021222324252627282930

每个app进程中物理内存共享手机处理器内存,物理内存是当真正需要使用时才会用到

以bitmap 为例子,创建空bitmap 时,会增加虚拟内存,但不会增加物理内存:

当bitmap 绘制内容,app进程的物理内存会变大,手机可用的物理内存在减少,直到OOM:

完整的测试验证代码:

package com.xingen.test.attemptdemo.oom;

import android.app.ActivityManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Debug;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : HeXinGen
 * @date : 2023/4/21
 * @description :
 * 用于检查内存状况
 * <p>
 * 参考:
 * 1.https://github.com/CharonChui/AndroidNote/blob/master/AdavancedPart/OOM%E9%97%AE%E9%A2%98%E5%88%86%E6%9E%90.md
 * 2.https://wenjie.store/archives/memory-knowledge-remake
 */
public class MemoryTask implements Runnable {

    private static final String TAG = "statisticsMemory ";
    private Handler memoryHandler;
    private int loopTime = 5 * 1000;
    private MonitorMemoryLeak leak;


    public MemoryTask() {
        this.leak = new MonitorMemoryLeak();
    }


    private static class MonitorMemoryLeak {
        private List<byte[]> jvmLeakList = new ArrayList<>();
        private List<Bitmap> nativeLeakList = new ArrayList<>();
        private Paint paint = new Paint();

        public void addJvmLeak() {
            byte[] largeByte = new byte[50 * 1024 * 1024];
            for (int i = 0; i < largeByte.length; ++i) {
                largeByte[i] = 'a';//分配使用时,进程内存中物理内存才会使用
            }
            Log.i(TAG, "byte size: " + (largeByte.length / 1024 / 1024) + " mB");
            jvmLeakList.add(largeByte);
        }

        public void addNativeLeak() {
            /**
             * 在android 8.0 以上版本, bitmap内存放到native层内存中,非jvm 堆内存中
             *
             * Bitmap.Config.ARGB_8888:一个像素占用4 byte
             * Bitmap的内存大小=像素*4byte
             */
            int width = 1024 * 8;
            int height = 1024 * 8;
            //bitmap 被创建时,会申请虚拟内存 256m=1024*8*1024*8*4
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            boolean draw=false;
            if (draw) {
                //当给bitmap绘制内容时,物理内存会增加; 物理内存是当真正需要使用时才会用到
                Canvas canvas = new Canvas(bitmap);
                paint.setAntiAlias(true);
                paint.setColor(Color.WHITE);
                canvas.drawCircle(width / 2, height / 2, width / 2, paint);
            }
            int pictureSize = bitmap.getByteCount() / 1024 / 1024;
            int bitmapSize = bitmap.getAllocationByteCount() / 1024 / 1024;
            Log.i(TAG, "bitmap size: " + bitmapSize + " mB" + " ,picture size: " + pictureSize + " mB");
            nativeLeakList.add(bitmap);
        }

        void release() {
            jvmLeakList.clear();
            nativeLeakList.clear();
        }

    }

    public enum  MonitorType{
         java_leak,native_leak,all_leak
    }
    private MonitorType type=MonitorType.java_leak;

    public MemoryTask setMonitorType(MonitorType type){
        this.type=type;
        return this;
    }

    public void startLoop() {
        if (memoryHandler == null) {
            HandlerThread thread = new HandlerThread("CheckMemoryThread");
            thread.start();
            memoryHandler = new Handler(thread.getLooper());
            memoryHandler.postDelayed(this, loopTime);
        }
    }

    @Override
    public void run() {
        switch (type){
            default:
                leak.addJvmLeak(); // 模拟增加jvm 内存泄漏
                leak.addNativeLeak(); //模拟增加native 内存泄漏
                break;
            case java_leak:
                leak.addJvmLeak(); // 模拟增加jvm 内存泄漏
                break;
            case native_leak:
                leak.addNativeLeak(); //模拟增加native 内存泄漏
                break;
        }
        Log.i(TAG, "start..........");
        JSONObject json = statisticsMemory();
        Log.i(TAG, "end..........");
        memoryHandler.postDelayed(this, loopTime);
    }

    public void stop() {
        memoryHandler.removeCallbacksAndMessages(null);
        memoryHandler.getLooper().quit();
        leak.release();
    }

    /**
     * 统计内存状况:
     *
     * @return
     */
    public JSONObject statisticsMemory() {
        JSONObject array = new JSONObject();
        try {
            JSONObject json1= statisticsJVMMemory();
            array.put("JVM", json1);
            Log.i(TAG,"jvm: "+json1.toString());
            JSONObject json2=statisticsNativeMemory();
            array.put("Native",json2);
            Log.i(TAG,"native: "+json2.toString());
            JSONObject json3= statisticsProcessMemory();
            array.put("Process",json3);
            Log.i(TAG,"app process: "+json3.toString());
            JSONObject json4=statisticsSystemMemory();
            array.put("System",json4 );
            Log.i(TAG,"system: "+json4.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return array;
    }

    /**
     * adb shell dumpsys meminfo packageName包名:
     * 查看每个进程中内存状况(包含jvm 和native 、shareLib)
     *
     * @return
     */
    private JSONObject statisticsNativeMemory() {
        JSONObject jsonObject = new JSONObject();
        long totalNative = Debug.getNativeHeapSize() / 1024 / 1024; // 当前进程中native层申请的堆内存,会随着时间而变化,加大或者减少
        long useNative = Debug.getNativeHeapAllocatedSize() / 1024 / 1024;//当进程中native层中已使用堆内存
        long freeNative = Debug.getNativeHeapFreeSize() / 1024 / 1024;//当前进程中native层中剩余的堆内存
        try {
            jsonObject.put(MemoryKeys.NativeKeys.key_native_total,totalNative+" mB");
            jsonObject.put(MemoryKeys.NativeKeys.key_native_use,useNative+" mB");
            jsonObject.put(MemoryKeys.NativeKeys.key_native_free,freeNative+" mB");
            jsonObject.put(MemoryKeys.NativeKeys.key_free_rate,getTwoDecimalPlaces(((float) freeNative/totalNative)));
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonObject;
    }
    public static interface   ProcCmd{
        String cmd_system_meminfo="/proc/meminfo"; //查看手机当前处理器内存状况
        String cmd_app_status="/proc/self/status";//当前进程中状况,内存、线程、fd等等;
        String cmd_app_limit="/proc/self/limits";//当前进程的限制,线程、fd的最大峰值
    }


    /**
     * 统计系统内存
     * MemTotal: 处理器内存,即多少G 运行内存
     * MemAvailable: 算法算出可用内存,包含可回收使用的内存 ,通常看这个
     * @return
     */
    public JSONObject statisticsSystemMemory() {
        JSONObject json = new JSONObject();
        //"/proc/meminfo"
        File file = new File(ProcCmd.cmd_system_meminfo);
        readFileLine(file, new Block() {
            long total, available;

            @Override
            public void block(String line) {
                try {
                    String s = null;
                    if (line.startsWith(MemoryKeys.SystemKeys.key_mem_total)) {
                        //手机处理器的内存,运行多少G
                        s = line;
                    } else if (line.startsWith(MemoryKeys.SystemKeys.key_mem_free)) {
                        //手机系统剩余内存,不包含可回收的内存。[MemTotal-MemFree]就是已被用掉的内存
                        s = line;
                    } else if (line.startsWith(MemoryKeys.SystemKeys.key_mem_available)) {
                        //手机系统可用内存:动态计算出的可用内存,包含mem_free + 可回收使用的内存,该值是一个估值。
                        s = line;
                    }/*else if (line.startsWith(MemoryKeys.SystemKeys.key_commit_limit)){
                        s=line;
                    }
                    else if (line.startsWith(MemoryKeys.SystemKeys.key_committed_as)){
                        s=line;
                    }*/
                    if (s != null) {
                        String[] array = s.split(":");
                        String value = array[1].trim().split(" kB")[0];
                        long size = Integer.valueOf(value) / 1024;
                        json.put(array[0], size + " mB");
                        if (s.startsWith(MemoryKeys.SystemKeys.key_mem_total)) {
                            total = size;
                        }
                        if (s.startsWith(MemoryKeys.SystemKeys.key_mem_available)) {
                            available = size;
                        }
                        if (total != 0 && available != 0) {
                            json.put(MemoryKeys.SystemKeys.key_free_rate, getTwoDecimalPlaces((float) available / total));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


        return json;
    }

    /**
     * 计算进程中内存状况和线程状况:
     * FDSize: 128  // 当前分配的文件描述符,这个值不是当前进程使用文件描述符的上线
     * VmPeak:  4403108 kB    // 当前进程运行过程中所占用内存的峰值
     * VmSize:  4402056 kB    // 已用逻辑空间地址,虚拟内存大小。整个进程使用虚拟内存大小,是VmLib, VmExe, VmData, 和 VmStk的总和。
     * VmLck:         0 kB
     * VmPin:         0 kB
     * VmHWM:     49108 kB    // 程序得到分配到物理内存的峰值
     * VmRSS:     48920 kB    // 程序现在正在使用的物理内存
     * RssAnon:            9268 kB
     * RssFile:           39540 kB
     * RssShmem:            112 kB
     * VmData:  1737808 kB        // 所占用的虚拟内存
     * VmStk:      8192 kB        // 任务在用户态的栈的大小 (stack_vm)
     * VmExe:        20 kB        // 程序所拥有的可执行虚拟内存的大小,代码段,不包括任务使用的库 (end_code-start_code)
     * VmLib:    163804 kB        // 被映像到任务的虚拟内存空间的库的大小 (exec_lib)
     * VmPTE:      1000 kB        // 该进程的所有页表的大小,单位:kb
     * Threads:        17        // 当前的线程数
     *
     * @return
     */
    public JSONObject statisticsProcessMemory() {

        JSONObject json = new JSONObject();
        // Linux 的/proc/self/status文件。这个并不是一个真实存在的文件,而为 Linux 的一个内核接口
        File file = new File(ProcCmd.cmd_app_status);
        readFileLine(file, (line) -> {
            try {
                String s = null;
                if (line.startsWith(MemoryKeys.ProcessKeys.key_threads)) {
                    //进程中线程的数量
                    s = line;
                } else if (line.startsWith(MemoryKeys.ProcessKeys.key_vm_size)) {
                    //整个进程中虚拟内存的总和(= VmLib+VmExe+VmData+VmStk),会动态变化增加
                    s = line;
                } else if (line.startsWith(MemoryKeys.ProcessKeys.key_vm_rss)) {
                    // 进程中当前物理内存,即系统实际在物理内存上分配给程序的内存
                    s = line;
                } else if (line.startsWith(MemoryKeys.ProcessKeys.key_vm_data)) {
                    s = line;
                } else if (line.startsWith(MemoryKeys.ProcessKeys.key_fd_size)) {
                    s = line;
                }/*else if (line.startsWith(MemoryKeys.ProcessKeys.key_vm_peek)){
                    s=line;
                }*/
                if (s != null) {
                    String[] array = s.split("\\t");
                    String name = array[0].split(":")[0];
                    String value = array[1].trim();
                    //进程中虚拟内存
                    json.put(name, value);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        return json;
    }

    private static interface Block {
        void block(String line);
    }

    private static void readFileLine(File file, Block block) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                } else {
                    if (block != null) {
                        block.block(line);
                    }
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(reader);
        }
    }

    private static void close(Closeable closeable) {
        try {
            if (closeable == null) {
                return;
            }
            closeable.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用于统计jvm 内存:
     * 1.最大限制内存
     * 2.申请的内存
     * 3.(申请的内存中)剩余使用的内存
     * 4.已使用的内存
     * 5.内存使用率
     *
     * @return
     */
    public JSONObject statisticsJVMMemory() {
        JSONObject json = new JSONObject();
        Runtime runtime = Runtime.getRuntime();
        //进程中最大jvm 内存大小
        long max_memory = runtime.maxMemory() / 1024;
        //进程中申请的jvm内存大小,不等用于一定分配那么多内存(会随着时间变化而变化)
        long apply_memory = runtime.totalMemory() / 1024;
        //进程中申请内存中可使用的jvm内存大小
        long free_memory = runtime.freeMemory() / 1024;
        //进程中已经使用的jvm 内存
        long use_memory = apply_memory - free_memory;
        //计算出jvm 的内存使用率,超过0.8就需要警惕
        float use_memory_rate = ((float) use_memory) / max_memory;
        //真正可用的内存,包含剩余可申请的内存
        long actual_free_memory=max_memory-use_memory;
        try {
            final String kB = " kB";
            json.put(MemoryKeys.JvmMemoryKeys.key_max_memory, max_memory + kB);
            json.put(MemoryKeys.JvmMemoryKeys.key_apply_memory, apply_memory + kB);
            json.put(MemoryKeys.JvmMemoryKeys.key_free_memory, free_memory + kB);
            json.put(MemoryKeys.JvmMemoryKeys.key_use_memory, use_memory + kB);
            json.put(MemoryKeys.JvmMemoryKeys.key_use_memory_rate, getTwoDecimalPlaces(use_memory_rate));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return json;
    }

    private static String getTwoDecimalPlaces(float value) {
        return String.format("%.2f", value) + "%";
    }

    interface MemoryKeys {

        interface JvmMemoryKeys {
            String key_max_memory = "maxMemory";
            String key_free_memory = "freeMemory";
            String key_use_memory = "useMemory";
            String key_apply_memory = "totalMemory";
            String key_use_memory_rate = "use_memory_rate";
        }

        interface ProcessKeys {
            String key_vm_size = "VmSize";//进程中虚拟内存总值
            String key_vm_rss = "VmRSS"; //进程中已经使用的物理内存
            String key_threads = "Threads";//当前进程中线程个数
            String key_fd_size = "FDSize"; //当前进程中fd 资源个数(包含file、socket)
            String key_vm_data = "VmData";// 当前进程中
            String key_vm_peek = "VmPeak";
        }

        interface SystemKeys {

            String key_mem_total = "MemTotal";
            String key_mem_free = "MemFree";
            String key_mem_available = "MemAvailable";
            String key_commit_limit = "CommitLimit"; // committed_as的阀值,限制最大值
            String key_committed_as = "Committed_AS";//所有进程申请内存总和,超过CommitLimit 越多越容易oom
            String key_free_rate = "free_memory_rate";// 手机可用内存率
        }

        interface NativeKeys {
            String key_native_total = "TotalNative";
            String key_native_free = "freeNative";
            String key_native_use="useNative";
            String key_free_rate = "free_memory_rate";// 手机可用内存率
        }
    }

}

  

使用方式:

 MemoryTask memoryTask = new MemoryTask().setMonitorType(MemoryTask.MonitorType.java_leak);
 memoryTask.startLoop();

资料参考