1. 程式人生 > >JVM 堆參數調優 (四)

JVM 堆參數調優 (四)

tin 計算 初始化 TP 12g ted out 垃圾 cit

堆參數調優

1、堆的結構

JAVA7

  堆邏輯上分為:新生區、養老區、永久區;實際上堆只有新生區、養老區

  Minor GC:輕量的垃圾回收; Major GC(Full GC):重量級垃圾回收。

  技術分享圖片

Java8

  沒有永久區了,被元空間取代;

  技術分享圖片

2、堆內存調優

  -Xms:設置初始分配大小,默認為物理內存的 “ 1 / 64”;

  -Xmx:最大分配內存,默認為物理內存的 “1 / 4”;

  -XX:+PrintGCDetails:輸出詳細的GC處理日誌;

 (1)使用代碼輸出實際默認的內存,代碼如下:

public class Demo1
{
    
public static void main(String[] args) { long totalMemory = Runtime.getRuntime().totalMemory(); //JVM中的初始內存總量 long maxMemory = Runtime.getRuntime().maxMemory(); //JVM試圖使用的最大內存 System.out.println("totalMemory = " + totalMemory + "Byte 、 " + (totalMemory / (double
) 1024 / 1024) + " MB"); System.out.println("MaxMemory = " + maxMemory + " Byte 、 " + (maxMemory / (double) 1024 / 1024) + " MB"); } }

  結果如下:(物理內存:12G

  totalMemory = 191365120Byte 、 182.5 MB // 182.5 * 64 / 1024

  MaxMemory = 2831679488 Byte 、 2700.5 MB // 2700.5 * 4 / 1024

  結論:發現默認的情況下分配的內存是總內存的 “1 / 4”、而初始化內存為 “1 / 64”。

(2)在IDEA中設置VM參數:

  VM 參數: -Xms1024M -Xmx1024M -XX:+PrintGCDetails

技術分享圖片

技術分享圖片

運行結果: 

  totalMemory = 1029177344Byte 、 981.5 MB //1024M

  MaxMemory = 1029177344 Byte 、 981.5 MB

  Heap

  PSYoungGen total 305664K, used 20971K [0x00000000eab00000, 0x0000000100000000, 0x0000000100000000)

  eden space 262144K, 8% used [0x00000000eab00000,0x00000000ebf7afb8,0x00000000fab00000)

  from space 43520K, 0% used [0x00000000fd580000,0x00000000fd580000,0x0000000100000000)

  to space 43520K, 0% used [0x00000000fab00000,0x00000000fab00000,0x00000000fd580000)

   ParOldGen total 699392K, used 0K [0x00000000c0000000, 0x00000000eab00000, 0x00000000eab00000)

  object space 699392K, 0% used [0x00000000c0000000,0x00000000c0000000,0x00000000eab00000)

  Metaspace used 3516K, capacity 4500K, committed 4864K, reserved 1056768K

  class space used 389K, capacity 392K, committed 512K, reserved 1048576K

計算堆內存: (305664 + 699392)/ 1024 = 981.5 MB

3、MMO異常的代碼:

為了更快的產生OOM,設置如下參數;

VM 參數: -Xms8M -Xmx8M -XX:+PrintGCDetails

public class Demo2
{
    public static void main(String[] args)
    {
        String str = "hello world";
        while(true)
        {
            str += str + new Random().nextInt(88888888)
                    + new Random().nextInt(999999999);
        }
    }
}

public class Demo1
{
public static void main(String[] args)
{
long totalMemory = Runtime.getRuntime().totalMemory(); //JVM中的初始內存總量
long maxMemory = Runtime.getRuntime().maxMemory(); //JVM試圖使用的最大內存

System.out.println("totalMemory = " + totalMemory + "Byte " +
(totalMemory / (double) 1024 / 1024) + " MB");
System.out.println("MaxMemory = " + maxMemory + " Byte " +
(maxMemory / (double) 1024 / 1024) + " MB");
}
}

JVM 堆參數調優 (四)