【深刻淺出-JVM】(7):棧上分配

概念

對那些做用於不會逃逸出方法的對象,在分配內存時,不在將對象分配在堆內存中,而是將對象屬性打散後分配在線程私有棧內存上,這樣隨着方法調用結束,棧上分配打散的對象也被回收掉,不在增長 GC 額外壓力。數據結構

Java 對象分配流程

示例

循環建立1000000000一個對象,阻止棧上分配app

棧上分配條件:開啓逃逸分析 & 開啓標量替換jvm

JVM 參數:函數

  • 棄用逃逸分析(不容許判斷對象是否能夠逃逸出函數體)

-server -Xmx10m -Xms10m -XX:-DoEscapeAnalysis -XX:+PrintGCspa

使用 server 模式棄用逃逸分析(-server -XX:-DoEscapeAnalysis),設置堆空間大小10m,初始空間10m,打印 GC 日誌線程

  • 棄用標量替換(不容許對象打散分配到棧上)

-server -Xmx10m -Xms10m -XX:+PrintGC -XX:-EliminateAllocations日誌

以上二選一code

代碼:server

package com.mousycoder.mycode.happy_jvm;



/**

 * @version 1.0

 * @author: mousycoder

 * @date: 2019-06-11 16:55

 */

public class OnStackTest {



    public static class User{

        public int id = 0;

        public String name = "";

    }



    public static void alloc(){

        User u = new User();

        u.id = 5;

        u.name = "mousycoder";

    }



    public static void main(String[] args) {

        long b = System.currentTimeMillis();

        for (int i = 0; i < 1000000000; i++) {

            alloc();

        }



        long e = System.currentTimeMillis();

        System.out.println(e-b);

    }

}

輸出:對象

[GC (Allocation Failure) 7651K->5603K(9728K), 0.0003680 secs]

[GC (Allocation Failure) 7651K->5603K(9728K), 0.0003829 secs]

[GC (Allocation Failure) 7651K->5603K(9728K), 0.0003809 secs]

[GC (Allocation Failure) 7651K->5603K(9728K), 0.0003731 secs]

[GC (Allocation Failure) 7651K->5603K(9728K), 0.0003286 secs]

VisualGC:

分析:

本次發生的是 Minor GC,發生 GC 的緣由是堆空間沒有合適的區域可以存放數據結構致使的,堆從7651K 回收到 5603K,

相關文章
相關標籤/搜索