天天看點

Java JVM 記憶體解析

文章目錄

  • ​​Java JVM 記憶體解析​​
  • ​​1、最大可用記憶體 -Xmx​​
  • ​​2、虛拟機中可用記憶體量​​
  • ​​3、虛拟機總記憶體量​​
  • ​​4、虛拟機目前實際可用記憶體​​
  • ​​5、Log 方法​​

Java JVM 記憶體解析

1、最大可用記憶體 -Xmx

設定虛拟機最大可以使用的記憶體總量

// JDK 源碼
    /**
     * Returns the maximum amount of memory that the Java virtual machine will
     * 傳回虛拟機設定的    -Xmx 值的記憶體量,如果不設定,預設情況下是電腦記憶體的1/4,一般情況下
     * 會不夠1/4,因為有一部分的實體記憶體要留給硬體,比如16G的記憶體,虛拟機預設記憶體就會在
     * 3600-3800M 左右
     *   
     * 如果沒有找到該值,這個方法就會傳回Long類型的最大值
     * attempt to use.  If there is no inherent limit then the value {@link
     * java.lang.Long#MAX_VALUE} will be returned.
     *
     * @return  the maximum amount of memory that the virtual machine will
     *          attempt to use, measured in bytes
     * @since 1.4
     */
    public native long maxMemory();
      
2、虛拟機中可用記憶體量

就是 JVM 目前空閑記憶體量 ,但是并不是最大記憶體減去已用記憶體就是可用記憶體

// JDK 源碼
    /**
     * Returns the amount of free memory in the Java Virtual Machine.
     * Calling the
     *          gc                 method may result in increasing the value returned
     * by          freeMemory.                
     *  
     * 傳回虛拟機中的可用記憶體量,當進行GC的時候,可能會導緻該值增加
     *
     * @return  an approximation to the total amount of memory currently
     *          available for future allocated objects, measured in bytes.
     */
    public native long freeMemory();
      
3、虛拟機總記憶體量
// JDK 源碼
    /**
     * Returns the total amount of memory in the Java virtual machine.
     * The value returned by this method may vary over time, depending on
     * the host environment.
     *       
4、虛拟機目前實際可用記憶體
private static final long MB = 1024 * 1024;
Runtime runtime = Runtime.getRuntime();
// 實際可用 = 最大可用 - 總計記憶體 + 空餘記憶體
( runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory()) / MB;
      
假設虛拟機設定最大記憶體4096MB,4G
虛拟機的 totalMemory 是2G,也就是占坑2G
其中,虛拟機正在運作的時候使用了1.2G,那麼 freeMemory 就是0.8G
虛拟機沒用到的記憶體,一共是 2G,占坑了但是沒有存放對象的是 0.8 G,
那麼,實際剩餘記憶體就是 4G - 2G + 0.8 G = 2.8G
      
5、Log 方法
private static final long MB = 1024 * 1024;

    /**
     * -Xmx   Java Heap最大值,預設值為實體記憶體的1/4,最佳設值應該視實體記憶體大小及計算機内其他記憶體開銷而定;
     *
     * -Xms   Java Heap初始值,Server端JVM最好将-Xms和-Xmx設為相同值,開發測試機JVM可以保留預設值;
     *
     * -Xmn   Java Heap Young區大小,不熟悉最好保留預設值;
     *
     * -Xss   每個線程的Stack大小,不熟悉最好保留預設值;
     *
     * 本方法用來監控 JVM 記憶體狀态
     */
    public static void currentMemory() {
        Runtime runtime = Runtime.getRuntime();
        log.info(" - - - - - - - - - - - - - - - - - - - - - - -");
        log.info("JVM 最大可用記憶體 -Xmx [{}] MB", runtime.maxMemory()/MB);
        log.info("JVM 目前可用記憶體 [{}] MB", runtime.freeMemory()/MB);
        log.info("JVM 目前總計記憶體 [{}] MB", runtime.totalMemory()/MB);
        log.info("JVM 實際可用記憶體 [{}] MB",( runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory())/MB);
        log.info(" - - - - - - - - - - - - - - - - - - - - - - -");
    }